<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";
dayjs.extend(customParseFormat)
dayjs.extend(isoWeek)
dayjs.extend(isBetween)

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

const itemInfo = ref({
  weeklyRegularWorkingHours: {}
})
const oldItemInfo = ref({})

const setupPage = async () => {

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

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

setupPage()

const emailSignature = ref(dataStore.activeProfile.emailSignature)
const tiptapLoaded = ref(false)
const contentSaved = ref(true)
const contentChanged = async (content) => {
  console.log(tiptapLoaded)
  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", dataStore.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: dataStore.activeProfile.email,
      name: dataStore.activeProfile.name,
      list_uuids: ["b97453fd-14b2-4b25-8f9b-b83847317ea3"],

    }
  })

  console.log(data)
}

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'
  }
})
</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'
        }
    ]"
  >
    <template #item="{item}">
      <UCard class="mt-5">
        <div v-if="item.label === 'Informationen'">
          <Toolbar>
            <UButton
                @click="dataStore.updateItem('profiles',{...itemInfo, fullName: itemInfo.firstName + ' ' + itemInfo.lastName},oldItemInfo)"
            >
              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="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>
          </InputGroup>

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

          <UButton
              v-if="dataStore.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="dataStore.updateItem('profiles',itemInfo)"
            >
              Speichern
            </UButton>
          </Toolbar>
          <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"
                @change="calcWeeklyWorkingHours"

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

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

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

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

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

              />
            </UFormGroup>
            <UFormGroup
              label="Sonntag"
              class="flex-auto"
            >
              <UInput
                v-model="itemInfo.weeklyRegularWorkingHours[7]"
                type="number"
                @change="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>
      </UCard>
    </template>
  </UTabs>
</template>

<style scoped>

</style>