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

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

const {times, projects} = storeToRefs(useDataStore())
const {fetchTimes} = useDataStore()

const timeInfo = ref({
  user: "",
  start: "",
  end: null,
  notes: null,
  projectId: null
})

const runningTimeInfo = 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 {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"
      >
        Stop
      </UButton>
      <UButton
          class="controlButton"
          @click="selectStartedTime"
      >
        Zeit Wählen
      </UButton>


      <div>
        Aktuelle gestarteter Eintrag:
        {{runningTimeInfo}}

        <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>{{ projects.find(project => project.id === runningTimeInfo.projectId) ? projects.find(project => project.id === runningTimeInfo.projectId).name : "" }}</span>
            </template>
          </USelectMenu>
        </UFormGroup>

      </div>


      <UTable :rows="times"/>

      {{timeInfo}}

    </div>
</template>

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