<script setup>
import 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 filterUser = ref(user.value.id || "")


const filteredRows = computed(() => {

  if(filterUser.value !== "" && dataStore.times) {
    return dataStore.times.filter(time => time.user === filterUser.value)
  } else {
    return dataStore.times
  }

})



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


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

const runningTimeInfo = ref({})
const showConfigTimeModal = ref(false)
const configTimeMode = ref("create")



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([itemInfo.value])
      .select()

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

  }
}

const updateTime = async () => {
  const {error} = await supabase
      .from("times")
      .update(itemInfo.value)
      .eq('id',itemInfo.value.id)

  if(error) {
    console.log(error)
  }

  toast.add({title: "Zeit erfolgreich gespeichert"})
  showConfigTimeModal.value = false
  await dataStore.fetchTimes()
}

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

  return `${dateFormat}`;
}

const getDuration = (time) => {
  const dez = dayjs(time.end).diff(time.start,'hour',true).toFixed(2)
  const hours = Math.floor(dez)
  const minutes = Math.floor((dez - hours) * 60)
  return {
    dezimal: dez,
    hours: hours,
    minutes: minutes,
    composed: `${hours}:${minutes}`
  }
}

const setState = async (newState) => {
  itemInfo.value.state = newState
  await updateTime()
}

</script>

<template>
  <InputGroup>
    <UButton
        @click="startTime"
        :disabled="runningTimeInfo.id"
    >
      Start
    </UButton>
    <UButton
        @click="stopStartedTime"
        :disabled="!runningTimeInfo.id"
    >
      Stop
    </UButton>
    <UButton
        @click="configTimeMode = 'create'; itemInfo = {start: new Date(), end: new Date()}; showConfigTimeModal = true"
    >
      Erstellen
    </UButton>
    <USelectMenu
      :options="dataStore.profiles"
      option-attribute="fullName"
      value-attribute="id"
      v-model="filterUser"
    >
      <template #label>
        {{dataStore.getProfileById(filterUser) ? dataStore.getProfileById(filterUser).fullName : "Kein Benutzer ausgewählt"}}
      </template>
    </USelectMenu>
  </InputGroup>

  <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="showConfigTimeModal"
  >
    <UCard>
      <template #header>
        Zeiteintrag {{configTimeMode === 'create' ?  "erstellen" : "bearbeiten"}}
      </template>
      <UFormGroup
          label="Start:"
      >
        <VueDatePicker
            v-model="itemInfo.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"
            :disabled="itemInfo.state !== 'Entwurf'"
        />
      </UFormGroup>
      <UFormGroup
          label="Ende:"
      >
        <VueDatePicker
            v-model="itemInfo.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"
            :disabled="itemInfo.state !== 'Entwurf'"
        />
      </UFormGroup>
      <!--          <UFormGroup
                  label="Dauer:"
                >
                  <UInput

                  />
                </UFormGroup>-->
      <UFormGroup
          label="Benutzer:"
      >
        <USelectMenu
            :options="dataStore.profiles"
            v-model="itemInfo.user"
            option-attribute="fullName"
            value-attribute="id"
            :disabled="itemInfo.state !== 'Entwurf'"
        >
          <template #label>
            {{dataStore.profiles.find(profile => profile.id === itemInfo.user) ? dataStore.profiles.find(profile => profile.id === itemInfo.user).firstName : "Benutzer auswählen"}}
          </template>
        </USelectMenu>
      </UFormGroup>
      <UFormGroup
          label="Projekt:"
      >
        <USelectMenu
            :options="dataStore.projects"
            v-model="itemInfo.projectId"
            option-attribute="name"
            value-attribute="id"
            searchable
            searchable-placeholder="Suche..."
            :search-attributes="['name']"
            :disabled="itemInfo.state !== 'Entwurf'"
        >
          <template #label>
            {{dataStore.projects.find(project => project.id === itemInfo.projectId) ? dataStore.projects.find(project => project.id === itemInfo.projectId).name : "Projekt auswählen"}}
          </template>
        </USelectMenu>
      </UFormGroup>
      <UFormGroup
          label="Typ:"
      >
        <USelectMenu
            v-model="itemInfo.type"
            :options="timeTypes"
            option-attribute="label"
            value-attribute="label"
            :disabled="itemInfo.state !== 'Entwurf'"
        >
          <template #label>
            {{itemInfo.type ? itemInfo.type : "Kategorie auswählen"}}
          </template>
        </USelectMenu>
      </UFormGroup>
      <UFormGroup
          label="Notizen:"
      >
        <UTextarea
            v-model="itemInfo.notes"
            :disabled="itemInfo.state !== 'Entwurf'"
        />
      </UFormGroup>


      <template #footer v-if="configTimeMode === 'create' || itemInfo.state === 'Entwurf'">
        <InputGroup>
          <UButton
              @click="createTime"
              v-if="configTimeMode === 'create'"
          >
            Erstellen
          </UButton>
          <UButton
              @click="updateTime"
              v-else-if="configTimeMode === 'edit'"
              v-if="itemInfo.state === 'Entwurf'"
          >
            Speichern
          </UButton>
          <UButton
              @click="setState('Eingereicht')"
              v-if="itemInfo.state === 'Entwurf'"
          >
            Einreichen
          </UButton>
        </InputGroup>

      </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' }"
      @select="(row) => {configTimeMode = 'edit';
        itemInfo = row;
        showConfigTimeModal = true}"
  >
    <template #state-data="{row}">
                <span
                    v-if="row.state === 'Entwurf'"
                    class="text-rose-500"
                >{{row.state}}</span>
      <span
          v-if="row.state === 'Eingereicht'"
          class="text-cyan-500"
      >{{row.state}}</span>
      <span
          v-if="row.state === 'Bestätigt'"
          class="text-primary-500"
      >{{row.state}}</span>
    </template>
    <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}">
      {{getDuration(row).composed}}
    </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>

</style>