<script setup>
import * as dayjs from "dayjs";
import VueDatePicker from '@vuepic/vue-datepicker'
import '@vuepic/vue-datepicker/dist/main.css'


definePageMeta({
  middleware: "auth"
})

const dataStore = useDataStore()
const supabase = useSupabaseClient()
const user = useSupabaseUser()
const toast = useToast()

const timeTypes = dataStore.getTimeTypes
const timeInfo = ref({
  user: "",
  start: "",
  end: null,
  notes: null,
  projectId: null,
  type: null
})

const filteredRows = computed(() => {

  if(user.value && dataStore.times) {
    return dataStore.times.filter(time => time.user === user.value.id)
  } else {
    return []
  }

})



const createTimeInfo = ref({
  user: "",
  start: new Date(),
  end: "",
  notes: null,
  projectId: null,
  type: null
})


const columns = [
  {
    key: "user",
    label: "Benutzer"
  },
  {
    key:"start",
    label:"Start"
  },
  {
    key:"type",
    label:"Typ"
  },
  {
    key: "end",
    label: "Ende"
  },
  {
    key: "duration",
    label: "Dauer"
  },
  {
    key: "projectId",
    label: "Projekt"
  },
  {
    key: "notes",
    label: "Notizen"
  }
]

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



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]
    await dataStore.fetchTimes()
    runningTimeInfo.value = dataStore.times.find(time => time.user === user.value.id && !time.end)
  }

}

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 = {}
    dataStore.fetchTimes()
  }
}

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


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

  if(error) {
    console.log(error)
  } else if(data) {
    createTimeInfo.value = {}
    toast.add({title: "Zeit erfolgreich erstellt"})
    showAddTimeModal.value = false
    await dataStore.fetchTimes()

  }
}

const format = (date) => {
  let dateFormat = dayjs(date).format("DD.MM.YY HH:mm")

  return `${dateFormat}`;
}
</script>

<template>
  <div class="flex items-center gap-1">
    <UButton
        class="controlButton"
        @click="startTime"
        :disabled="runningTimeInfo.id"
    >
      Start
    </UButton>
    <UButton
        class="controlButton"
        @click="stopStartedTime"
        :disabled="!runningTimeInfo.id"
    >
      Stop
    </UButton>
    <UButton
        class="controlButton"
        @click="showAddTimeModal = true"
    >
      Erstellen
    </UButton>
  </div>

  <div v-if="runningTimeInfo.id" class="mt-3">

    Start: {{dayjs(runningTimeInfo.start).format("DD.MM.YY HH:mm")}}

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

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


    <UFormGroup
        label="Kategorie:"
    >
      <USelectMenu
          v-model="runningTimeInfo.type"
          :options="timeTypes"
          option-attribute="label"
          value-attribute="label"
      >
        <template #label>
          {{runningTimeInfo.type ? runningTimeInfo.type : "Kategorie auswählen"}}
        </template>
      </USelectMenu>
    </UFormGroup>
  </div>

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

      <UFormGroup
          label="Start:"
      >
        <VueDatePicker
            v-model="createTimeInfo.start"
            locale="de"
            cancel-text="Abbrechen"
            select-text="Auswählen"
            now-button-label="Jetzt"
            text-input="MM.dd.yyyy HH:mm"
            :dark="useColorMode().value !== 'light'"
            :format="format"
            :preview-format="format"
        />
      </UFormGroup>
      <UFormGroup
          label="Ende:"
      >
        <VueDatePicker
            v-model="createTimeInfo.end"
            locale="de"
            cancel-text="Abbrechen"
            select-text="Auswählen"
            now-button-label="Jetzt"
            text-input="MM.dd.yyyy HH:mm"
            :dark="useColorMode().value !== 'light'"
            :format="format"
            :preview-format="format"
        />
      </UFormGroup>
      <!--          <UFormGroup
                  label="Dauer:"
                >
                  <UInput

                  />
                </UFormGroup>-->
      <UFormGroup
          label="Benutzer:"
      >
        <USelectMenu
            :options="dataStore.profiles"
            v-model="createTimeInfo.user"
            option-attribute="firstName"
            value-attribute="id"
        >
          <template #label>
            {{dataStore.profiles.find(profile => profile.id === createTimeInfo.user) ? dataStore.profiles.find(profile => profile.id === createTimeInfo.user).firstName : "Benutzer auswählen"}}
          </template>
        </USelectMenu>
      </UFormGroup>
      <UFormGroup
          label="Projekt:"
      >
        <USelectMenu
            :options="dataStore.projects"
            v-model="createTimeInfo.projectId"
            option-attribute="name"
            value-attribute="id"
        >
          <template #label>
            {{dataStore.projects.find(project => project.id === createTimeInfo.projectId) ? dataStore.projects.find(project => project.id === createTimeInfo.projectId).name : "Projekt auswählen"}}
          </template>
        </USelectMenu>
      </UFormGroup>
      <UFormGroup
          label="Typ:"
      >
        <USelectMenu
            v-model="runningTimeInfo.type"
            :options="timeTypes"
            option-attribute="label"
            value-attribute="label"
        >
          <template #label>
            {{runningTimeInfo.type ? runningTimeInfo.type : "Kategorie auswählen"}}
          </template>
        </USelectMenu>
      </UFormGroup>
      <UFormGroup
          label="Notizen:"
      >
        <UTextarea
            v-model="createTimeInfo.notes"
        />
      </UFormGroup>


      <template #footer>
        <UButton
            @click="createTime"
        >
          Erstellen
        </UButton>
      </template>
    </UCard>
  </UModal>

  <UDivider class="mt-3"/>

  <UTable
      class="mt-3"
      :columns="columns"
      :rows="filteredRows"
      :empty-state="{ icon: 'i-heroicons-circle-stack-20-solid', label: 'Noch keine Einträge' }"
  >
    <template #user-data="{row}">
      {{dataStore.profiles.find(profile => profile.id === row.user) ? dataStore.profiles.find(profile => profile.id === row.user).fullName : row.user }}
    </template>

    <template #start-data="{row}">
      {{dayjs(row.start).format("DD.MM.YY HH:mm")}}
    </template>
    <template #end-data="{row}">
      {{dayjs(row.end).format("DD.MM.YY HH:mm")}}
    </template>
    <template #duration-data="{row}">
      {{`${String(dayjs(row.end).diff(row.start,'hour',true).toFixed(2)).replace(".",",")} h`}}
    </template>
    <template #projectId-data="{row}">
      {{dataStore.projects.find(project => project.id === row.projectId) ? dataStore.projects.find(project => project.id === row.projectId).name : ""}}
    </template>
  </UTable>
</template>

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