<script setup>
import dayjs from "dayjs";

definePageMeta({
  middleware: "auth"
})


//TODO: Build User Page



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({})

const tabItems = [
  {
    label: "Informationen"
  },{
    label: "Zeiterfassung"
  },{
    label: "Rechte"
  },
]

const timeSelection = ref("Heute")
const timeColumns = [
  {
    key: "state",
    label: "Status"
  },{
    key: "user",
    label: "Benutzer"
  },{
    key: "start",
    label: "Start"
  },{
    key: "end",
    label: "Ende"
  },{
    key: "notes",
    label: "Notizen"
  },{
    key: "projectId",
    label: "Projekt"
  },{
    key: "duration",
    label: "Dauer"
  },
]

const filteredTimes = computed(() => {
  let rows = dataStore.times
  rows = rows.filter(i => i.user === currentItem.id)

  if(timeSelection.value === 'Heute') {
    rows = rows.filter(i => dayjs().isSame(i.start,'day'))
  } else if(timeSelection.value === 'Diese Woche') {
    rows = rows.filter(i => dayjs().isSame(i.start,'week'))
  } else if(timeSelection.value === 'Dieser Monat') {
    rows = rows.filter(i => dayjs().isSame(i.start,'month'))
  } else if(timeSelection.value === 'Dieses Jahr') {
    rows = rows.filter(i => dayjs().isSame(i.start,'year'))
  } else if(timeSelection.value === 'Letztes Jahr') {
    rows = rows.filter(i => dayjs().subtract(1,'year').isSame(i.start,'year'))
  }

  return rows
})

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

  itemInfo.value = currentItem



}

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

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

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

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

const updateItem = async () => {
  itemInfo.value.fullName = `${itemInfo.value.firstName} ${itemInfo.value.lastName}`
  const {error} = await supabase
      .from("profiles")
      .update(itemInfo.value)
      .eq('id',itemInfo.value.id)

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


  router.push(`/users/show/${currentItem.id}`)
  toast.add({title: "Mitarbeiter erfolgreich gespeichert"})
  dataStore.fetchProfiles()
}

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 getSelectionSum = computed(() => {
  let times = filteredTimes.value
  let sum = 0
  let sumEntwurf = 0
  let sumEingereicht = 0
  let sumBestaetigt = 0

  times.forEach(time => {
    let duration = getDuration(time)

    sum += Number(duration.dezimal)

    if(time.state === 'Entwurf') {
      sumEntwurf += Number(duration.dezimal)
    } else if(time.state === 'Eingereicht') {
      sumEingereicht += Number(duration.dezimal)
    } else if(time.state === 'Bestätigt') {
      sumBestaetigt += Number(duration.dezimal)
    }
  })

  sum = sum.toFixed(2)
  sumEntwurf = sumEntwurf.toFixed(2)
  sumEingereicht = sumEingereicht.toFixed(2)
  sumBestaetigt = sumBestaetigt.toFixed(2)

  return {
    sum,
    sumEntwurf,
    sumEingereicht,
    sumBestaetigt
  }
})




setupPage()
</script>

<template>
  <div>
    <UCard v-if="currentItem && mode == 'show'" >
      <template #header>
        {{currentItem.fullName}}
      </template>

      <UTabs :items="tabItems">
        <template #item="{item}">
          <div
            v-if="item.label === 'Informationen'"
            class="w-full"
          >
            <InputGroup class="w-full">
              <div class="w-1/2 mr-5">
                <UFormGroup
                  label="Anrede"
                >
                  <UInput/>
                </UFormGroup>

                <InputGroup>
                  <UFormGroup
                      label="Vorname:"
                      class="flex-auto"
                  >
                    <UInput
                      v-model="itemInfo.firstName"
                    />
                  </UFormGroup>
                  <UFormGroup
                      label="Nachnahme:"
                      class="flex-auto"
                  >
                    <UInput
                        v-model="itemInfo.lastName"
                    />
                  </UFormGroup>
                </InputGroup>

                <UFormGroup
                  label="Geburtsdatum"
                >
                  <UInput/>
                </UFormGroup>
                <UFormGroup
                  label="Benutzername"
                >
                  <UInput
                      v-model="itemInfo.username"
                      disabled
                  />
                </UFormGroup>
              </div>
              <div class="w-1/2">
                <UFormGroup
                  label="E-Mail"
                >
                  <UInput/>
                </UFormGroup>

                <InputGroup>
                  <UFormGroup
                      label="Telefonnummer:"
                      class="w-1/2"
                  >
                    <UInput/>
                  </UFormGroup>
                  <UFormGroup
                      label="Mobilfunknummer:"
                      class="w-1/2"
                  >
                    <UInput/>
                  </UFormGroup>
                </InputGroup>

                <UFormGroup
                  label="Straße & Hausnummer"
                >
                  <UInput
                    class="flex-auto"
                  />
                </UFormGroup>

                <InputGroup>
                  <UFormGroup
                      label="Postleitzahl:"
                      class="w-40"
                  >
                    <UInput/>
                  </UFormGroup>
                  <UFormGroup
                      label="Ort:"
                      class="flex-auto"
                  >
                    <UInput/>
                  </UFormGroup>
                </InputGroup>
              </div>
            </InputGroup>
            <UButton
              class="mt-5"
              @click="updateItem"
            >
              Speichern
            </UButton>

          </div>
          <div v-else-if="item.label === 'Zeiterfassung'">
            <UButtonGroup>
              <UButton
                @click="timeSelection = 'Heute'"
                :variant="timeSelection === 'Heute' ? 'solid' : 'outline'"
              >
                Heute
              </UButton>
              <UButton
                  @click="timeSelection = 'Diese Woche'"
                  :variant="timeSelection === 'Diese Woche' ? 'solid' : 'outline'"
              >
                Diese Woche
              </UButton>
              <UButton
                  @click="timeSelection = 'Dieser Monat'"
                  :variant="timeSelection === 'Dieser Monat' ? 'solid' : 'outline'"
              >
                Dieser Monat
              </UButton>
              <UButton
                  @click="timeSelection = 'Dieses Jahr'"
                  :variant="timeSelection === 'Dieses Jahr' ? 'solid' : 'outline'"
              >
                Dieses Jahr
              </UButton>
              <UButton
                  @click="timeSelection = 'Letztes Jahr'"
                  :variant="timeSelection === 'Letztes Jahr' ? 'solid' : 'outline'"
                  color="rose"
              >
                Letztes Jahr
              </UButton>
            </UButtonGroup>
            <UButton
              class="ml-3"
              to="/employees/timetracking"
            >
              Zur Zeiterfassung
            </UButton>

            <InputGroup class="w-full">
              <div>
                Summe: {{getSelectionSum.sum}}<br>
                Summe Entwurf: {{getSelectionSum.sumEntwurf}}<br>
                Summe Eingereicht: {{getSelectionSum.sumEingereicht}}<br>
                Summe Bestätigt: {{getSelectionSum.sumBestaetigt}}<br>
              </div>
            </InputGroup>

            <UTable
              :rows="filteredTimes"
              :columns="timeColumns"
            >
              <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 #start-data="{row}">
                <div class="text-right">{{dayjs(row.start).format("DD.MM.YY HH:mm")}}</div>
              </template>
              <template #end-data="{row}">
                <div class="text-right">{{dayjs(row.end).format("HH:mm")}}</div>
              </template>
              <template #user-data="{row}">
                {{dataStore.getProfileById(row.user) ? dataStore.getProfileById(row.user).fullName : ""}}
              </template>
              <template #duration-data="{row}">
                <div class="text-right">{{ getDuration(row).composed}} Std</div>
              </template>
              <template #projectId-data="{row}">
                {{dataStore.getProjectById(row.projectId) ? dataStore.getProjectById(row.projectId).name : ""}}
              </template>
            </UTable>


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









      <template #footer>
        <UButton
            v-if="mode == 'show' && currentItem.id"
            @click="editItem"
        >
          Bearbeiten
        </UButton>
      </template>



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

      <UFormGroup
          label="Titel:"
      >
        <UInput
            v-model="itemInfo.title"
        />
      </UFormGroup>

      <UFormGroup
          label="Status:"
      >
        <USelectMenu
            v-model="itemInfo.state"
            :options="states"
        />
      </UFormGroup>

      <UFormGroup
          label="Kundennummer:"
      >
        <USelectMenu
            v-model="itemInfo.customer"
            :options="dataStore.customers"
            option-attribute="name"
            value-attribute="id"
            searchable
            :search-attributes="['name']"
        >
          <template #label>
            {{dataStore.customers.find(customer => customer.id === itemInfo.customer) ? dataStore.customers.find(customer => customer.id === itemInfo.customer).name : "Kunde auswählen"}}
          </template>
        </USelectMenu>
      </UFormGroup>


      <UFormGroup
          label="Beschreibung:"
      >
        <UTextarea
            v-model="itemInfo.description"
        />
      </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>