<script setup>
import dayjs from "dayjs";

const profileStore = useProfileStore();
const supabase = useSupabaseClient()
const toast = useToast()

const runningTimeInfo = ref({})

const projects = ref([])
const platform = ref("default")

const setupPage = async () => {
    runningTimeInfo.value = (await supabase.from("times").select().eq("profile", profileStore.activeProfile.id).is("endDate", null).single()).data || {}

    projects.value = (await useSupabaseSelect("projects"))

    if(await useCapacitor().getIsPhone()) {
      platform.value = "mobile"
    }

}

setupPage()

/*if(dataStore.workingtimes.find(time => time.profile === profileStore.activeProfile.id && !time.endDate)) {
  runningTimeInfo.value = dataStore.workingtimes.find(time => time.profile === profileStore.activeProfile.id && !time.end)
}*/

const startTime = async () => {
  console.log("started")
  runningTimeInfo.value = {
    profile: profileStore.activeProfile.id,
    startDate: dayjs(),
    tenant: profileStore.currentTenant,
    state: platform.value === "mobile" ? "In der App gestartet" : "Im Web gestartet",
    source: "Dashboard"
  }

  const {data,error} = await supabase
      .from("times")
      .insert([runningTimeInfo.value])
      .select()
  if(error) {
    console.log(error)
    toast.add({title: "Fehler beim starten der Projektzeit",color:"rose"})
  } else if(data) {
    toast.add({title: "Projektzeit erfolgreich gestartet"})
    runningTimeInfo.value = data[0]
    //console.log(runningTimeInfo.value)
  }
}

const stopStartedTime = async () => {
  runningTimeInfo.value.endDate = dayjs()
  runningTimeInfo.value.state = platform.value === "mobile" ? "In der App gestoppt" : "Im Web gestoppt"

  const {error,status} = await supabase
      .from("times")
      .update(runningTimeInfo.value)
      .eq('id',runningTimeInfo.value.id)

  if(error) {
    console.log(error)
    let errorId = await useError().logError(`${status} - ${JSON.stringify(error)}`)
    toast.add({title: errorId ? `Fehler beim stoppen der Projektzeit (Fehler ID: ${errorId})` : `Fehler beim stoppen der Projektzeit`,color:"rose"})


  } else {
    toast.add({title: "Projektzeit erfolgreich gestoppt"})
    runningTimeInfo.value = {}
  }
}


</script>

<template>
  <div v-if="runningTimeInfo.startDate">
    <p>Start: {{dayjs(runningTimeInfo.startDate).format("HH:mm")}}</p>
    <p>Dauer: {{dayjs().diff(dayjs(runningTimeInfo.startDate),'minutes') > 59 ? `${Math.floor(dayjs().diff(dayjs(runningTimeInfo.startDate),'minutes') / 60)}:${dayjs().diff(dayjs(runningTimeInfo.startDate),'minutes') % 60} h` : dayjs().diff(dayjs(runningTimeInfo.startDate),'minutes') + ' min' }}</p>

    <UFormGroup
        class="mt-2"
        label="Notizen:"
    >
      <UTextarea
          v-model="runningTimeInfo.notes"
      />
    </UFormGroup>
    <UFormGroup
        class="mt-2"
        label="Projekt:"
    >
      <USelectMenu
          v-model="runningTimeInfo.project"
          :options="projects"
          searchable
          :search-attributes="['name','notes','customer']"
          searchable-placeholder="Suche"
          value-attribute="id"
          option-attribute="name"
      />
    </UFormGroup>
    <UButton
        class="mt-3"
        @click="stopStartedTime"
        :disabled="!runningTimeInfo.id"
    >
      Stop
    </UButton>
  </div>
  <div v-else>
    <p>Keine Projektzeit gestartet</p>
    <UButton
        class="mt-3"
      @click="startTime"
    >Starten</UButton>
  </div>
</template>

<style scoped>

</style>