<script setup>
definePageMeta({
  middleware: "auth"
})

const supabase = useSupabaseClient()
const user = useSupabaseUser()
const toast = useToast()
console.log(user)

const {times, projects} = storeToRefs(useDataStore())
const {fetchTimes, getTimeTypes} = useDataStore()
const timeTypes = getTimeTypes
const timeInfo = ref({
  user: "",
  start: "",
  end: null,
  notes: null,
  projectId: null,
  type: null
})

const runningTimeInfo = ref({

})
const showAddTimeModal = ref(false)
const addTimeInfo = ref({

})


const startTime = async () => {
  console.log("started")
  timeInfo.value.user = user.value.id
  timeInfo.value.start = new Date().toISOString()

  const {data,error} = await supabase
      .from("times")
      .insert([timeInfo.value])
      .select()

  if(error) {
    console.log(error)
  } else if(data) {
    timeInfo.value = data[0]
    fetchTimes()
  }

  console.log(data)
  console.log(error)

}

const stopStartedTime = async () => {
  console.log(runningTimeInfo.value)

  runningTimeInfo.value.end = new Date().toISOString()

  const mapNumRange = (num, inMin, inMax, outMin, outMax) =>
      ((num - inMin) * (outMax - outMin)) / (inMax - inMin) + outMin;

  runningTimeInfo.value.duration = Math.round(mapNumRange(Math.abs(new Date(runningTimeInfo.value.end) - new Date(runningTimeInfo.value.start))/1000/60,0,60,0,1)*100)/100

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

  if(error) {
    console.log(error)
  } else {
    toast.add({title: "Zeit erfolgreich gestoppt"})
    runningTimeInfo.value = {}
    fetchTimes()
  }
}

const selectStartedTime = () => {
  runningTimeInfo.value = times.value.find(time => time.user == user.value.id && !time.end)
}

//selectStartedTime()

</script>

<template>
    <div>
      <UButton
          class="controlButton"
          @click="startTime"
          :disabled="runningTimeInfo.id"
      >
        Start
      </UButton>
      <UButton
          class="controlButton"
          @click="stopStartedTime"
          :disabled="!runningTimeInfo.id"
      >
        Stop
      </UButton>
      <UButton
          class="controlButton"
          @click="selectStartedTime"
      >
        Zeit Wählen
      </UButton>
      <UButton
          class="controlButton"
          @click="showAddTimeModal = true"
      >
        Erstellen
      </UButton>

      <UModal
        v-model="showAddTimeModal"
      >
        <UCard>
          <template #header>
            Zeiteintrag erstellen
          </template>

          <UFormGroup
            label="Start:"
          >

          </UFormGroup>
          <UFormGroup
            label="Ende:"
          >

          </UFormGroup>
          <UFormGroup
            label="Dauer:"
          >
            <UInput

            />
          </UFormGroup>
          <UFormGroup
            label="Benutzer:"
          >
            <USelectMenu/>
          </UFormGroup>
          <UFormGroup
            label="Projekt:"
          >
            <USelectMenu/>
          </UFormGroup>
          <UFormGroup
            label="Typ:"
          >
            <USelectMenu/>
          </UFormGroup>
          <UFormGroup
            label="Notizen:"
          >
            <UTextarea/>
          </UFormGroup>


          <template #footer>
            <UButton>
              Erstellen
            </UButton>
          </template>
        </UCard>
      </UModal>

      <div>

        <div class="mt-3">
          Aktuelle gestarteter Eintrag:
          {{runningTimeInfo.id ? runningTimeInfo : "Keine Zeit gewählt"}}



        </div>

        <div v-if="runningTimeInfo.id">
          <UFormGroup
              label="Notizen:"
          >
            <UTextarea
                v-model="runningTimeInfo.notes"
            />
          </UFormGroup>

          <UFormGroup
              label="Projekt:"
          >
            <USelectMenu
                :options="projects"
                option-attribute="name"
                value-attribute="id"
                v-model="runningTimeInfo.projectId"
            >
              <template #label>
                <span v-if="runningTimeInfo.projectId">{{ projects.find(project => project.id === runningTimeInfo.projectId) ? projects.find(project => project.id === runningTimeInfo.projectId).name : "" }}</span>
                <span v-else>Projekt auswählen</span>
              </template>
            </USelectMenu>
          </UFormGroup>

          <UFormGroup
              label="Kategorie:"
          >
            <USelectMenu
                v-model="runningTimeInfo.type"
                :options="timeTypes"
                option-attribute="label"
                value-attribute="label"
            />
          </UFormGroup>
        </div>





      </div>

      <UDivider class="mt-3"/>

      <UTable
          class="mt-3"
          v-if="times && user"
          :rows="times.filter(time => time.user === user.id)"
      />

    </div>
</template>

<style scoped>
.controlButton {
  margin-right: 1em;
}
</style>