<script setup>
import dayjs from "dayjs";
import customParseFormat from "dayjs/plugin/customParseFormat"
import {useCapacitor} from "~/composables/useCapacitor.js";
import {setPageLayout} from "#app";
import FloatingActionButton from "~/components/mobile/FloatingActionButton.vue";

dayjs.extend(customParseFormat)



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

const platform = await useCapacitor().getIsPhone() ? "mobile" : "default"


const filterUser = ref(profileStore.activeProfile.id || "")

const workingtimes = ref([])

const setupPage = async () => {
  if(platform === "mobile") {
    setPageLayout("mobile")
  }

  if(route.query) {
    if(route.query.profile) filterUser.value = route.query.profile
  }

  workingtimes.value = (await supabase.from("workingtimes").select().eq("profile",filterUser.value).order("startDate",{ascending: false})).data




}

const changeFilterUser = async () => {
  await router.push(`/workingtimes/?profile=${filterUser.value}`)
  await setupPage()
}

setupPage()






const filteredRows = computed(() => {

  let times = workingtimes.value

  times = times.filter(i => i.profile === filterUser.value)


  return times/*.map(i => {
    return {
      ...i,
      disabledExpand: i.approved
    }
  })*/

})



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


const columns = [
  {
    key:"state",
    label: "Status"
  },
  {
    key: "approved",
    label: "Genehmigt"
  },
  {
    key: "profile",
    label: "Mitarbeiter"
  },
  {
    key: "date",
    label: "Datum"
  },
  {
    key:"startDate",
    label:"Start"
  },
  {
    key: "endDate",
    label: "Ende"
  },
  {
    key: "duration",
    label: "Dauer"
  },
  {
    key: "notes",
    label: "Notizen"
  }
]





const getDuration = (time) => {
  const minutes = Math.floor(dayjs(time.endDate).diff(dayjs(time.startDate),'minutes',true))
  const hours = Math.floor(minutes/60)
  return {
    //dezimal: dez,
    hours: hours,
    minutes: minutes,
    composed: `${hours}:${String(minutes % 60).padStart(2,"0")} h`
  }
}

const updateWorkingTime = async (data) => {
  await dataStore.updateItem('workingtimes',data)
  await setupPage()
}

const toggleRow = (row) => {
  if(expand.value.openedRows.includes(row)){
    expand.value.openedRows = []
  } else {
    expand.value.openedRows = [row]
  }
}

const expand = ref({
  openedRows: [],
  row: {}
})

const setEndDate = (row) => {
  row.startDate = dayjs(row.startDate).toISOString()

  row.endDate = dayjs(row.endDate).set("year", dayjs(row.startDate).get("year")).set("month", dayjs(row.startDate).get("month")).set("date", dayjs(row.startDate).get("date"))

  row.endDate = dayjs(row.endDate).toISOString()
}

</script>

<template>
  <FloatingActionButton
      :label="`+ Anwesenheit`"
      variant="outline"
      v-if="platform === 'mobile'"
      @click="router.push(`/workingtimes/create`)"
      :pos="0"
  />
  <FloatingActionButton
      :label="`Auswertung`"
      variant="outline"
      v-if="platform === 'mobile'"
      @click="router.push(`/workingtimes/evaluate/${profileStore.activeProfile.id}`)"
      :pos="1"
  />
  <UDashboardNavbar title="Anwesenheiten" v-if="platform !== 'mobile'">
    <template #right>
      <UButton
          @click="router.push(`/workingtimes/edit?profile=${filterUser}`)"
      >
        + Anwesenheit
      </UButton>
    </template>
  </UDashboardNavbar>
  <UDashboardNavbar title="Anwesenheiten" v-else>
    <template #toggle>
      <div></div>
    </template>
  </UDashboardNavbar>
  <UDashboardToolbar v-if="platform !== 'mobile'">
    <template #left>

      <USelectMenu
          :options="profileStore.profiles"
          option-attribute="fullName"
          value-attribute="id"
          v-model="filterUser"
          @change="changeFilterUser"
      >
        <template #label>
          {{profileStore.getProfileById(filterUser) ? profileStore.getProfileById(filterUser).fullName : "Kein Benutzer ausgewählt"}}
        </template>
      </USelectMenu>
      <UButton
        @click="router.push(`/workingtimes/evaluate/${filterUser}`)"
      >
        Auswertung
      </UButton>
    </template>
  </UDashboardToolbar>

  <UTable
      class="mt-3"
      :columns="columns"
      :rows="filteredRows"
      :empty-state="{ icon: 'i-heroicons-circle-stack-20-solid', label: 'Noch keine Einträge' }"
      @select="(i) => toggleRow(i)"
      v-model:expand="expand"
      :multiple-expand="false"

  >
    <template #expand="{ row }">
      <InputGroup class="p-4">
        <UTooltip text="Genehmigen & Speichern" v-if="!row.approved">
          <UButton
              @click="updateWorkingTime({...row, approved: true})"
              icon="i-heroicons-check"
          />
        </UTooltip>
        <UTooltip text="Speichern"  v-if="!row.approved">
          <UButton
              @click="updateWorkingTime(row)"
              icon="i-mdi-content-save"
              variant="outline"
          />
        </UTooltip>
        <UTooltip text="Bearbeiten">
          <UButton
              @click="router.push(`/workingtimes/edit/${row.id}`)"
              variant="outline"
              icon="i-heroicons-pencil-solid"
          />
        </UTooltip>
      </InputGroup>
      <div class="p-4" v-if="!row.approved">
        <UFormGroup label="Start:">
          <UPopover :popper="{ placement: 'bottom-start' }">
            <UButton
                icon="i-heroicons-calendar-days-20-solid"
                :label="row.startDate ? dayjs(row.startDate).format('HH:mm') : 'Datum auswählen'"
                variant="outline"
            />

            <template #panel="{ close }">
              <LazyDatePicker v-model="row.startDate" @close="setEndDate(row)" mode="dateTime"/>
            </template>
          </UPopover>
        </UFormGroup>
        <UFormGroup label="Ende:">
          <UPopover :popper="{ placement: 'bottom-start' }">
            <UButton
                :disabled="!row.endDate"
                variant="outline"
                icon="i-heroicons-calendar-days-20-solid"
                :label="row.endDate ? dayjs(row.endDate).format('HH:mm') : 'Datum auswählen'"
            />

            <template #panel="{ close }">
              <LazyDatePicker v-model="row.endDate" @close="close" mode="time"/>
            </template>
          </UPopover>
        </UFormGroup>
        <UFormGroup
            label="Notizen:"
        >
          <UTextarea
              v-model="row.notes"
          />
        </UFormGroup>



      </div>
      <div class="px-4 pb-4" v-else>
        <p><span class="font-bold">Mitarbeitende/r:</span> {{profileStore.getProfileById(row.profile).fullName}}</p>
        <p><span class="font-bold">Start:</span> {{dayjs(row.startDate).format("DD.MM.YYYY HH:mm")}}</p>
        <p><span class="font-bold">Ende:</span> {{dayjs(row.endDate).format("DD.MM.YYYY HH:mm")}}</p>
        <p><span class="font-bold">Genehmigt:</span> {{row.approved ? "Ja" : "Nein"}}</p>
        <p><span class="font-bold">Notizen:</span> {{row.notes}}</p>
      </div>
    </template>
    <template #profile-data="{row}">
      {{profileStore.profiles.find(profile => profile.id === row.profile) ? profileStore.profiles.find(profile => profile.id === row.profile).fullName : row.profile }}
    </template>
    <template #approved-data="{row}">
      <span v-if="row.approved" class="text-primary-500">Ja</span>
      <span v-else class="text-rose-600">Nein</span>
    </template>
    <template #date-data="{row}">
      {{dayjs(row.startDate).format("DD.MM.YYYY")}}
    </template>
    <template #startDate-data="{row}">
      {{dayjs(row.startDate).format("HH:mm")}} Uhr
    </template>
    <template #endDate-data="{row}">
      {{row.endDate ? dayjs(row.endDate).format("HH:mm") + " Uhr" : ""}}
    </template>
    <template #duration-data="{row}">
      {{row.endDate ? getDuration(row).composed : ""}}
    </template>
  </UTable>
</template>

<style scoped>

</style>