<script setup>
import dayjs from "dayjs";
import customParseFormat from "dayjs/plugin/customParseFormat"

dayjs.extend(customParseFormat)

definePageMeta({
  middleware: "auth"
})

const dataStore = useDataStore()
const supabase = useSupabaseClient()
const user = useSupabaseUser()
const toast = useToast()
const router = useRouter()


const timeInfo = ref({
  profile: "",
  start: "",
  end: null,
  notes: null,
})

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

const workingtimes = ref([])

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

setupPage()






const filteredRows = computed(() => {

  let times = workingtimes.value

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

  /*if(dataStore.hasRight('viewTimes')) {
    if(filterUser.value !== "") {
      times = times.filter(i => i.profile === filterUser.value)
    }
  } else if(dataStore.hasRight('viewOwnTimes')) {
    times = times.filter(i => i.profile === dataStore.getOwnProfile.id)
  } else {
    times  = []
  }*/

  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",
    sortable:true
  },
  {
    key: "approved",
    label: "Genehmigt",
    sortable:true
  },
  {
    key: "profile",
    label: "Mitarbeiter",
    sortable:true
  },
  {
    key: "date",
    label: "Datum",
    sortable:true
  },
  {
    key:"startDate",
    label:"Start",
    sortable:true
  },
  {
    key: "endDate",
    label: "Ende",
    sortable:true
  },
  {
    key: "duration",
    label: "Dauer",
    sortable:true
  },
  {
    key: "notes",
    label: "Notizen",
    sortable:true
  }
]

console.log(dataStore.workingtimes)

const runningTimeInfo = ref({})

const startTime = async () => {
  console.log("started")
  timeInfo.value = {
    profile: dataStore.activeProfile.id,
    startDate: dayjs(),
    tenant: dataStore.currentTenant,
    state: "Im Web gestartet"
  }

  const {data,error} = await supabase
      .from("workingtimes")
      .insert([timeInfo.value])
      .select()
  if(error) {
    console.log(error)
  } else if(data) {
    //timeInfo.value = data[0]
    await dataStore.fetchWorkingTimes()
    runningTimeInfo.value = timeInfo.value//dataStore.times.find(time => time.profile === dataStore.activeProfile.id && !time.endDate)
  }
}

const stopStartedTime = async () => {
  runningTimeInfo.value.endDate = dayjs()
  runningTimeInfo.value.state = "Im Web gestoppt"

  const {data,error} = await supabase
      .from("workingtimes")
      .update(runningTimeInfo.value)
      .eq('id',runningTimeInfo.value.id)
      .select()
  console.log(data)

  if(error) {
    console.log(error)
  } else {
    toast.add({title: "Zeit erfolgreich gestoppt"})
    runningTimeInfo.value = {}
    dataStore.fetchWorkingTimes()
  }
}

if(dataStore.workingtimes.find(time => time.profile === dataStore.activeProfile.id && !time.endDate)) {
  runningTimeInfo.value = dataStore.workingtimes.find(time => time.profile === dataStore.activeProfile.id && !time.end)
}

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

</script>

<template>
  <UDashboardNavbar title="Anwesenheiten">
    <template #right>
      <UButton
          @click="startTime"
          :disabled="runningTimeInfo.id "
      >
        Start
      </UButton>
      <UButton
          @click="router.push(`/workingtimes/edit`)"
      >
        Erstellen
      </UButton>
    </template>
  </UDashboardNavbar>
  <UDashboardToolbar>
    <template #left>

      <USelectMenu
          v-if="dataStore.hasRight('viewTimes')"
          :options="dataStore.profiles"
          option-attribute="fullName"
          value-attribute="id"
          v-model="filterUser"
          @change="setupPage"
      >
        <template #label>
          {{dataStore.getProfileById(filterUser) ? dataStore.getProfileById(filterUser).fullName : "Kein Benutzer ausgewählt"}}
        </template>
      </USelectMenu>
      <UButton
        @click="router.push(`/workingtimes/evaluate/${filterUser}`)"
      >
        Auswertung
      </UButton>
    </template>
  </UDashboardToolbar>
  <div class="mx-3">
    <UAlert
        v-if="runningTimeInfo.startDate && !runningTimeInfo.endDate"
        class="my-3"
        title="Laufende Zeit:"
    >
      <template #description>
        <p>Start: {{dayjs(runningTimeInfo.startDate).format("HH:mm")}}</p>
        <p>Dauer: {{dayjs().diff(dayjs(runningTimeInfo.startDate),'minutes') > 59 ? `${Math.floor(dayjs().diff(dayjs(runningTimeInfo.startDate),'minutes') / 60)}:${dayjs().diff(dayjs(runningTimeInfo.startDate),'minutes') % 60} h` : dayjs().diff(dayjs(runningTimeInfo.startDate),'minutes') + ' min' }}</p>

        <UFormGroup
            class="mt-2"
            label="Notizen:"
        >
          <UTextarea
              v-model="runningTimeInfo.notes"
          />
        </UFormGroup>
        <UButton
            class="mt-3"
            @click="stopStartedTime"
            :disabled="!runningTimeInfo.id"
        >
          Stop
        </UButton>
      </template>
    </UAlert>
  </div>

  <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="row.endDate = row.startDate" 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> {{dataStore.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}">
      {{dataStore.profiles.find(profile => profile.id === row.profile) ? dataStore.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>