<script setup>
import dayjs from "dayjs";

definePageMeta({
  middleware: "auth"
})

const dataStore = useDataStore()
const supabase = useSupabaseClient()
const route = useRoute()
const router = useRouter()
const toast = useToast()
const id = ref(route.params.id ? route.params.id : null )

let currentItem = null

//Working
const mode = ref(route.params.mode || "show")
const itemInfo = ref({
  approved: null
})
const states = ["Offen","Genehmigt", "Abgelehnt"]

const absenceReasons = [
    "Elternzeit",
    "Kind krank - Kinderbetreuung",
    "Krankheit",
    "Krankheit 1 Tag (mit Attest)",
    "Krankheit ab 2. Tag (mit Attest)",
    "Mutterschutz",
    "Sonderurlaub (bezahlt)",
    "Überstundenausgleich",
    "Unbezahlter Urlaub",
    "Urlaub"
]

//Functions
const setupPage = () => {
  if(mode.value === "show" || mode.value === "edit"){
    currentItem = dataStore.getAbsenceRequestById(Number(useRoute().params.id))
  }

  if(mode.value === "edit") itemInfo.value = currentItem



}

const createItem = async () => {
  const {data,error} = await supabase
      .from("absenceRequests")
      .insert([itemInfo.value])
      .select()

  if(error) {
    console.log(error)
  } else {
    mode.value = "show"
    itemInfo.value = {
      id: 0,
    }
    toast.add({title: "Abwesenheit erfolgreich erstellt"})
    await dataStore.fetchAbsenceRequests()
    router.push(`/employees/absenceRequests/show/${data[0].id}`)
    setupPage()
  }
}

const editItem = async () => {
  router.push(`/employees/absenceRequests/edit/${currentItem.id}`)
  setupPage()
}

const cancelEditorCreate = () => {
  mode.value = "show"
  itemInfo.value = {
    id: 0,
    infoData: {}
  }
}

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

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


  router.push(`/employees/absenceRequests/show/${currentItem.id}`)
  toast.add({title: "Abwesenheit erfolgreich gespeichert"})
  dataStore.fetchAbsenceRequests()
}



setupPage()
</script>

<template>
  <div>
    <UCard v-if="currentItem && mode == 'show'" >
      <template #header>
        <UBadge
            v-if="currentItem.approved === 'Offen'"
            color="blue"
        >{{currentItem.approved}}</UBadge>
        <UBadge
            v-else-if="currentItem.approved === 'Genehmigt'"
            color="primary"
        >{{currentItem.approved}}</UBadge>
        <UBadge
            v-else-if="currentItem.approved === 'Abgelehnt'"
            color="rose"
        >{{currentItem.approved}}</UBadge>



        {{currentItem.reason}}
      </template>

      <span>Mitarbeiter: {{dataStore.profiles.find(item => item.id === currentItem.user) ? dataStore.profiles.find(item => item.id === currentItem.user).fullName : ""}}<br></span>
      <span>Start: {{dayjs(currentItem.start).format("DD.MM.YYYY")}}<br></span>
      <span>Ende: {{dayjs(currentItem.end).format("DD.MM.YYYY")}}<br></span>

      Notizen:<br>
      {{currentItem.note}}<br>





      <template #footer>
        <UButton
            v-if="mode == 'show' && currentItem.id"
            @click="editItem"
        >
          Bearbeiten
        </UButton>
        <UButton
            color="red"
            class="ml-2"
            disabled
        >
          Archivieren
        </UButton>
        <!-- TODO: Kunde archivieren        -->
      </template>



    </UCard>
    <UCard v-else-if="mode == 'edit' || mode == 'create'" >
      <template #header v-if="mode === 'edit'">
        {{itemInfo.reason}}
      </template>

      <UFormGroup
          label="Status:"
      >
        <USelectMenu
            v-model="itemInfo.approved"
            :options="states"
            option-attribute="label"
            value-attribute="value"
        />
      </UFormGroup>

      <UFormGroup
          label="Grund:"
      >
        <USelectMenu
            v-model="itemInfo.reason"
            :options="absenceReasons"
        />
      </UFormGroup>

      <UFormGroup
          label="Mitarbeiter:"
      >
        <USelectMenu
            v-model="itemInfo.user"
            :options="dataStore.profiles"
            option-attribute="fullName"
            value-attribute="id"
            searchable
            :search-attributes="['fullName']"
        >
          <template #label>
            {{dataStore.profiles.find(item => item.id === itemInfo.user) ? dataStore.profiles.find(item => item.id === itemInfo.user).fullName : "Mitarbeiter auswählen"}}
          </template>
        </USelectMenu>
      </UFormGroup>

      <UFormGroup label="Start:">
        <UPopover :popper="{ placement: 'bottom-start' }">
          <UButton icon="i-heroicons-calendar-days-20-solid" :label="itemInfo.start ? dayjs(itemInfo.start).format('DD.MM.YYYY') : 'Datum auswählen'" />

          <template #panel="{ close }">
            <LazyDatePicker v-model="itemInfo.start" @close="close" />
          </template>
        </UPopover>
      </UFormGroup>

      <UFormGroup label="Ende:">
        <UPopover :popper="{ placement: 'bottom-start' }">
          <UButton icon="i-heroicons-calendar-days-20-solid" :label="itemInfo.end ? dayjs(itemInfo.end).format('DD.MM.YYYY') : 'Datum auswählen'" />

          <template #panel="{ close }">
            <LazyDatePicker v-model="itemInfo.end" @close="close" />
          </template>
        </UPopover>
      </UFormGroup>


      <UFormGroup
          label="Notizen:"
      >
        <UTextarea
            v-model="itemInfo.note"
        />
      </UFormGroup>


      <template #footer>
        <UButton
            v-if="mode == 'edit'"
            @click="updateItem"
        >
          Speichern
        </UButton>
        <UButton
            v-else-if="mode == 'create'"
            @click="createItem"
        >
          Erstellen
        </UButton>
        <UButton
            @click="cancelEditorCreate"
            color="red"
            class="ml-2"
        >
          Abbrechen
        </UButton>
      </template>

    </UCard>
  </div>
</template>

<style scoped>

</style>