<script setup>
import axios from "axios"
import HistoryDisplay from "~/components/HistoryDisplay.vue";
import dayjs from "dayjs";
import customParseFormat from "dayjs/plugin/customParseFormat";
import isoWeek from "dayjs/plugin/isoWeek"
import isBetween from "dayjs/plugin/isBetween"
import DocumentList from "~/components/DocumentList.vue";
import DocumentUpload from "~/components/DocumentUpload.vue";
import { v4 as uuidv4 } from 'uuid';
dayjs.extend(customParseFormat)
dayjs.extend(isoWeek)
dayjs.extend(isBetween)

const dataStore = useDataStore()
const profileStore = useProfileStore()
const route = useRoute()
const router = useRouter()
const supabase = useSupabaseClient()
const toast = useToast()

const itemInfo = ref({
  weeklyRegularWorkingHours: {
    "1":0,
    "2":0,
    "3":0,
    "4":0,
    "5":0,
    "6":0,
    "7":0,
  }
})
const oldItemInfo = ref({})

const setupPage = async () => {

  console.log(itemInfo.value)

  if(route.params.id) {
    itemInfo.value = await useSupabaseSelectSingle("profiles",route.params.id,"*, documents(*), checks(*)")

    if(Object.keys(itemInfo.value.weeklyRegularWorkingHours).length === 0) {
      itemInfo.value.weeklyRegularWorkingHours = {
        "1":0,
        "2":0,
        "3":0,
        "4":0,
        "5":0,
        "6":0,
        "7":0,
      }
    }

    if(!itemInfo.value.weeklyWorkingHours) itemInfo.value.weeklyWorkingHours = 0
    if(!itemInfo.value.weeklyWorkingDays) itemInfo.value.weeklyWorkingDays = 0
    if(!itemInfo.value.annualPaidLeaveDays) itemInfo.value.annualPaidLeaveDays = 0

  }

  if(itemInfo.value.id) oldItemInfo.value = JSON.parse(JSON.stringify(itemInfo.value))
}

setupPage()

const emailSignature = ref(profileStore.activeProfile.emailSignature)
const tiptapLoaded = ref(false)
const contentSaved = ref(true)
const contentChanged = async (content) => {
  emailSignature.value = content.html
  if(tiptapLoaded.value === true) {
    contentSaved.value = false
  } else {
    tiptapLoaded.value = true
  }
}



const saveSignature = async () => {
  const {data,error} = await supabase.from("profiles").update({emailSignature: emailSignature.value}).eq("id", profileStore.activeProfile.id)

  if(error) {
    toast.add({title: "Fehler beim Speichern der Signatur", color:"rose"})
  }
  else {
    contentSaved.value = true
  }
}



const addToNewsletter = async () => {
  const {data,error} = await axios({
    url: "https://newsletter.fedeo.io/api/public/subscription",
    method: "post",
    data: {
      email: profileStore.activeProfile.email,
      name: profileStore.activeProfile.name,
      list_uuids: ["b97453fd-14b2-4b25-8f9b-b83847317ea3"],

    }
  })

}

const calcWeeklyWorkingHours = () => {
  itemInfo.value.weeklyWorkingHours =
      itemInfo.value.weeklyRegularWorkingHours[1] +
      itemInfo.value.weeklyRegularWorkingHours[2] +
      itemInfo.value.weeklyRegularWorkingHours[3] +
      itemInfo.value.weeklyRegularWorkingHours[4] +
      itemInfo.value.weeklyRegularWorkingHours[5] +
      itemInfo.value.weeklyRegularWorkingHours[6] +
      itemInfo.value.weeklyRegularWorkingHours[7]
}

const colorMode = useColorMode()
const isLight = computed({
  get() {
    return colorMode.value !== 'dark'
  },
  set() {
    colorMode.preference = colorMode.value === 'dark' ? 'light' : 'dark'
  }
})

const saveProfile = async () => {
  let data = {...itemInfo.value, fullName: itemInfo.value.firstName + ' ' + itemInfo.value.lastName}
  delete data.checks
  delete data.documents

  await dataStore.updateItem('profiles',data,oldItemInfo.value)
}

const addAutomaticHourCorrection = async () => {
  itemInfo.value.automaticHourCorrections.push({mode: 'correct', id: uuidv4(), weekday: 1, bookingTimeUTC: {hour: 0, minute: 0}, rangeStartUTC: {hour: 0, minute: 0}, rangeEndUTC: {hour: 0, minute: 0}})
}

</script>

<template>
  <UDashboardNavbar
    :title="itemInfo.fullName"
  >
    <template #left>
      <UButton
          icon="i-heroicons-chevron-left"
          variant="outline"
          @click="router.push(`/profiles`)"
      >
        Mitarbeiter
      </UButton>
    </template>
    <template #center>
      <h1
          v-if="itemInfo"
          :class="['text-xl','font-medium'/*, ... true ? ['text-primary'] : ['text-rose-500']*/]"
      >{{itemInfo ? `Mitarbeiter: ${itemInfo.fullName}` : ''}}</h1>
    </template>
  </UDashboardNavbar>
  <UTabs
      v-if="itemInfo.id"
    class="p-5"
    :items="[
        {
          label: 'Informationen'
        },{
          label: 'Logbuch'
        },{
          label: 'Zeiterfassung'
        },{
          label: 'Vertragsdaten'
        },{
          label: 'Dokumente'
        },{
          label: 'Überprüfungen'
        }
    ]"
  >
    <template #item="{item}">
      <UCard class="mt-5">
        <div v-if="item.label === 'Informationen'">
          <Toolbar>
            <UButton
                @click="saveProfile"
            >
              Speichern
            </UButton>
          </Toolbar>
          <InputGroup class="w-full">
            <UFormGroup
              label="Anrede"
              class="w-60"
            >
              <UInput
                v-model="itemInfo.salutation"
              />
            </UFormGroup>
            <UFormGroup
              label="Vorname"
              class="flex-auto"
            >
              <UInput
                v-model="itemInfo.firstName"
              />
            </UFormGroup>
            <UFormGroup
              label="Nachname"
              class="flex-auto"
            >
              <UInput
                v-model="itemInfo.lastName"
              />
            </UFormGroup>
          </InputGroup>
          <InputGroup class="w-full">
            <UFormGroup
              label="Mitarbeiternummer"
              class="w-60"
            >
              <UInput
                v-model="itemInfo.employeeNumber"
              />
            </UFormGroup>
            <UFormGroup
              label="E-Mail"
              class="flex-auto"
            >
              <UInput
                v-model="itemInfo.email"
              />
            </UFormGroup>
            <UFormGroup
              label="Benutzername"
              class="flex-auto"
            >
              <UInput
                v-model="itemInfo.username"
              />
            </UFormGroup>
          </InputGroup>
          <InputGroup class="w-full">
            <UFormGroup
              label="Festnetz Telefon"
              class="w-60"
            >
              <UInput
                v-model="itemInfo.fixedTel"
              />
            </UFormGroup>
            <UFormGroup
              label="Handy"
              class="flex-auto"
            >
              <UInput
                v-model="itemInfo.mobileTel"
              />
            </UFormGroup>
            <UFormGroup
                label="Geburtstag:"
            >
              <UPopover :popper="{ placement: 'bottom-start' }">
                <UButton
                    icon="i-heroicons-calendar-days-20-solid"
                    :label="itemInfo.birthday ? dayjs(itemInfo.birthday).format('DD.MM.YYYY') : 'Datum auswählen'"
                    variant="outline"
                />

                <template #panel="{ close }">
                  <LazyDatePicker v-model="itemInfo.birthday" />
                </template>
              </UPopover>
            </UFormGroup>
          </InputGroup>
          <InputGroup class="w-full">
            <UFormGroup
              label="Kleidergröße Oberteil"
              class="w-60"
            >
              <UInput
                v-model="itemInfo.clothingSizeTop"
              />
            </UFormGroup>
            <UFormGroup
              label="Kleidergröße Hose"
              class="w-60"
            >
              <UInput
                v-model="itemInfo.clothingSizeBottom"
              />
            </UFormGroup>
            <UFormGroup
              label="Schuhgröße"
              class="w-60"
            >
              <UInput
                v-model="itemInfo.clothingSizeShoe"
              />
            </UFormGroup>
          </InputGroup>

          <UDivider class="my-5" v-if="profileStore.activeProfile.id === itemInfo.id">
            Helligkeitseinstellung
          </UDivider>

          <UButton
              v-if="profileStore.activeProfile.id === itemInfo.id"
              :icon="isLight ? 'i-heroicons-moon-20-solid' : 'i-heroicons-sun-20-solid'"
              color="white"
              variant="outline"
              aria-label="Theme"
              @click="isLight = !isLight"
          >
            {{!isLight ? "Hell" : "Dunkel"}}
          </UButton>

          <UDivider class="my-5">
            E-Mail Signatur
          </UDivider>

          <UButton
            variant="outline"
            v-if="!contentSaved"
            @click="saveSignature"
          >
            Speichern
          </UButton>

          <Tiptap
              @updateContent="contentChanged"
              :preloadedContent="emailSignature"
          />

          <!--<UDivider>Newsletter</UDivider>

          <UButton
            @click="addToNewsletter"
            variant="outline"
          >
            In Newsletter eintragen
          </UButton>-->

        </div>
        <div v-if="item.label === 'Logbuch'">
          <HistoryDisplay
              type="profile"
              v-if="itemInfo"
              :element-id="itemInfo.id"
          />
        </div>
        <div v-if="item.label === 'Vertragsdaten'">
          <Toolbar>
            <UButton
                @click="saveProfile"
            >
              Speichern
            </UButton>
          </Toolbar>
          <InputGroup class="w-full">
            <UFormGroup
                label="Eintrittsdatum:"
            >
              <UPopover :popper="{ placement: 'bottom-start' }">
                <UButton
                    icon="i-heroicons-calendar-days-20-solid"
                    :label="itemInfo.entryDate ? dayjs(itemInfo.entryDate).format('DD.MM.YYYY') : 'Datum auswählen'"
                    variant="outline"
                />

                <template #panel="{ close }">
                  <LazyDatePicker v-model="itemInfo.entryDate" />
                </template>
              </UPopover>
            </UFormGroup>
          </InputGroup>
          <InputGroup class="w-full">
            <UFormGroup
              label="Wöchentliche Arbeitszeit"
              class="flex-auto"
            >
              <UInput
                v-model="itemInfo.weeklyWorkingHours"
                type="number"
              />
            </UFormGroup>
<!--            <UFormGroup
              label="Durchschnittliche Arbeitstage pro Woche"
              class="flex-auto"
            >
              <UInput
                v-model="itemInfo.weeklyWorkingDays"
              />
            </UFormGroup>-->
            <UFormGroup
              label="Urlaubstage"
              class="flex-auto"
            >
              <UInput
                v-model="itemInfo.annualPaidLeaveDays"
              />
            </UFormGroup>
          </InputGroup>
          <UDivider class="my-3">Regelarbeitszeiten</UDivider>
          <InputGroup class="w-full">
            <UFormGroup
              label="Montag"
              class="flex-auto"
            >
              <UInput
                v-model="itemInfo.weeklyRegularWorkingHours[1]"
                type="number"
                @keyup="calcWeeklyWorkingHours"
                @change="calcWeeklyWorkingHours"

              />
            </UFormGroup><UFormGroup
              label="Dienstag"
              class="flex-auto"
            >
              <UInput
                v-model="itemInfo.weeklyRegularWorkingHours[2]"
                type="number"
                @change="calcWeeklyWorkingHours"
                @keyup="calcWeeklyWorkingHours"

              />
            </UFormGroup>
            <UFormGroup
              label="Mittwoch"
              class="flex-auto"
            >
              <UInput
                v-model="itemInfo.weeklyRegularWorkingHours[3]"
                type="number"
                @change="calcWeeklyWorkingHours"
                @keyup="calcWeeklyWorkingHours"
              />
            </UFormGroup>
            <UFormGroup
              label="Donnerstag"
              class="flex-auto"
            >
              <UInput
                v-model="itemInfo.weeklyRegularWorkingHours[4]"
                type="number"
                @change="calcWeeklyWorkingHours"
                @keyup="calcWeeklyWorkingHours"
              />
            </UFormGroup>
            <UFormGroup
              label="Freitag"
              class="flex-auto"
            >
              <UInput
                v-model="itemInfo.weeklyRegularWorkingHours[5]"
                type="number"
                @change="calcWeeklyWorkingHours"
                @keyup="calcWeeklyWorkingHours"
              />
            </UFormGroup>
            <UFormGroup
              label="Samstag"
              class="flex-auto"
            >
              <UInput
                v-model="itemInfo.weeklyRegularWorkingHours[6]"
                type="number"
                @change="calcWeeklyWorkingHours"
                @keyup="calcWeeklyWorkingHours"
              />
            </UFormGroup>
            <UFormGroup
              label="Sonntag"
              class="flex-auto"
            >
              <UInput
                v-model="itemInfo.weeklyRegularWorkingHours[7]"
                type="number"
                @change="calcWeeklyWorkingHours"
                @keyup="calcWeeklyWorkingHours"
              />
            </UFormGroup>
          </InputGroup>
        </div>
        <div v-else-if="item.label === 'Dokumente'">
          <DocumentUpload
              type="profile"
              :element-id="itemInfo.id"
          />

          <DocumentList :documents="dataStore.getDocumentsByProfileId(itemInfo.id)"/>
        </div>
        <div v-else-if="item.label === 'Überprüfungen'">
          <UTable
              :rows="itemInfo.checks"
              :columns="[{key:'name',label: 'Name'},{key:'rhythm',label: 'Rhythmus'},{key:'description',label: 'Beschreibung'}]"
              class="w-full"
              :ui="{ divide: 'divide-gray-200 dark:divide-gray-800' }"
              @select="(i) => router.push(`/checks/show/${i.id}`) "
              :empty-state="{ icon: 'i-heroicons-circle-stack-20-solid', label: 'Keine Überprüfungen anzuzeigen' }"
          >
            <template #rhythm-data="{row}">
              {{row.distance}}
              <span v-if="row.distanceUnit === 'dayjs'">Tage</span>
              <span v-if="row.distanceUnit === 'years'">Jahre</span>
            </template>
          </UTable>
        </div>
        <div v-else-if="item.label === 'Zeiterfassung'">
          <UButton
            @click="addAutomaticHourCorrection"
          >
            + Korrektur
          </UButton>
          <UButton
            @click="saveProfile"
            class="ml-3"
          >
            Speichern
          </UButton>

          <UDivider class="my-3" />

          <InputGroup class="w-full" v-for="item in itemInfo.automaticHourCorrections">
            <UFormGroup
              label="Modus"
            >
              <USelectMenu
                v-model="item.mode"
                :options="[{key: 'correct', label: 'Korrigieren'},{key: 'automatic-checkout', label: 'Automatisches ausbuchen'}]"
                option-attribute="label"
                value-attribute="key"
                class="w-80"
              />
            </UFormGroup>
            <UFormGroup
              label="Wochentag"
            >
              <USelectMenu
                  v-model="item.weekday"
                  :options="[{key: 1, label: 'Montag'},{key: 2, label: 'Dienstag'},{key: 3, label: 'Mittwoch'},{key: 4, label: 'Donnerstag'},{key: 5, label: 'Freitag'},{key: 6, label: 'Samstag'},{key: 7, label: 'Sonntag'},]"
                  option-attribute="label"
                  value-attribute="key"
                  class="w-40"
              />
            </UFormGroup>
            <UFormGroup
              label="Zeitraum Start"
              v-if="item.mode === 'correct'"
            >
              <InputGroup>
                <UInput
                    v-model="item.rangeStartUTC.hour"
                    placeholder="Stunde UTC"
                    class="w-20"
                />
                <UInput
                    v-model="item.rangeStartUTC.minute"
                    placeholder="Minute UTC"
                    class="w-20"
                />
              </InputGroup>

            </UFormGroup>
            <UFormGroup
              label="Zeitraum Ende"
              v-if="item.mode === 'correct'"
            >
              <InputGroup>
                <UInput
                    v-model="item.rangeEndUTC.hour"
                    placeholder="Stunde UTC"
                    class="w-20"
                />
                <UInput
                    v-model="item.rangeEndUTC.minute"
                    placeholder="Minute UTC"
                    class="w-20"
                />
              </InputGroup>
            </UFormGroup>
            <UFormGroup
              label="Korrigieren zu"
              v-if="item.mode === 'correct'"
            >
              <InputGroup>
                <UInput
                    v-model="item.bookingTimeUTC.hour"
                    placeholder="Stunde UTC"
                    class="w-20"
                />
                <UInput
                    v-model="item.bookingTimeUTC.minute"
                    placeholder="Minute UTC"
                    class="w-20"
                />
              </InputGroup>
            </UFormGroup>
            <UFormGroup
              label="Ausbuchen"
              v-if="item.mode === 'automatic-checkout'"
            >
              <InputGroup>
                <UInput
                    v-model="item.bookingTimeUTC.hour"
                    placeholder="Stunde UTC"
                    class="w-20"
                />
                <UInput
                    v-model="item.bookingTimeUTC.minute"
                    placeholder="Minute UTC"
                    class="w-20"
                />
              </InputGroup>
            </UFormGroup>
            <UFormGroup
              label="Entfernen"
            >
              <UButton
                  icon="i-heroicons-x-mark"
                  variant="outline"
                  color="red"
                  @click="itemInfo.automaticHourCorrections = itemInfo.automaticHourCorrections.filter(i => i.id !== item.id)"
              />
            </UFormGroup>

          </InputGroup>

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

<style scoped>

</style>