<script setup>
import dayjs from "dayjs";
import VueDatePicker from '@vuepic/vue-datepicker'
import '@vuepic/vue-datepicker/dist/main.css'


definePageMeta({
  middleware: "auth"
})

const dataStore = useDataStore()
const profileStore = useProfileStore()
const supabase = useSupabaseClient()
const user = useSupabaseUser()
const toast = useToast()


const timeTypes = dataStore.getTimeTypes
const timeInfo = ref({
  profile: "",
  startDate: "",
  endDate: null,
  notes: null,
  project: null,
  type: null
})

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

const times = ref([])

const setup = async () => {
  times.value = await useSupabaseSelect("times","*, profile(*)")
}

setup()

const filteredRows = computed(() => {

  //let times = times.value

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

  return times.value

})



const itemInfo = ref({
  user: "",
  start: new Date(),
  end: "",
  notes: null,
  projectId: null,
  type: null,
  state: "Entwurf"
})


const columns = [
  {
    key:"state",
    label: "Status",
  },
  {
    key: "user",
    label: "Benutzer",
  },
  {
    key:"startDate",
    label:"Start",
  },
  {
    key: "endDate",
    label: "Ende",
  },
  {
    key:"type",
    label:"Typ",
  },
  {
    key: "duration",
    label: "Dauer",
  },
  {
    key: "project",
    label: "Projekt",
  },
  {
    key: "notes",
    label: "Notizen",
  }
]

const runningTimeInfo = ref({})
const showConfigTimeModal = ref(false)
const configTimeMode = ref("create")



const startTime = async () => {
  console.log("started")
  timeInfo.value.profile = profileStore.activeProfile.id
  timeInfo.value.start = new Date().toISOString()
  timeInfo.value.tenant = profileStore.currentTenant

  const {data,error} = await supabase
      .from("times")
      .insert([timeInfo.value])
      .select()

  if(error) {
    console.log(error)
  } else if(data) {
    //timeInfo.value = data[0]
    await dataStore.fetchTimes()
    runningTimeInfo.value = dataStore.times.find(time => time.profile === profileStore.activeProfile.id && !time.end)
  }

}

const stopStartedTime = async () => {
  console.log(runningTimeInfo.value)

  runningTimeInfo.value.end = new Date().toISOString()

  const mapNumRange = (num, inMin, inMax, outMin, outMax) =>
      ((num - inMin) * (outMax - outMin)) / (inMax - inMin) + outMin;

  runningTimeInfo.value.duration = Math.round(mapNumRange(Math.abs(new Date(runningTimeInfo.value.end) - new Date(runningTimeInfo.value.start))/1000/60,0,60,0,1)*100)/100

  const {data,error} = await supabase
      .from("times")
      .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.fetchTimes()
  }
}

if(times.value.find(time => time.profile == profileStore.activeProfile.id && !time.end)) {
  runningTimeInfo.value = times.value.find(time => time.profile == profileStore.activeProfile.id && !time.end)
}


const createTime = async () => {
  const {data,error} = await supabase
      .from("times")
      .insert({...itemInfo.value, tenant: profileStore.currentTenant})
      .select()

  if(error) {
    console.log(error)
  } else if(data) {
    itemInfo.value = {}
    toast.add({title: "Zeit erfolgreich erstellt"})
    showConfigTimeModal.value = false
    await dataStore.fetchTimes()

  }
}

const updateTime = async () => {
  const {error} = await supabase
      .from("times")
      .update(itemInfo.value)
      .eq('id',itemInfo.value.id)

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

  toast.add({title: "Zeit erfolgreich gespeichert"})
  showConfigTimeModal.value = false
  await dataStore.fetchTimes()
}

const format = (date) => {
  let dateFormat = dayjs(date).format("DD.MM.YY HH:mm")

  return `${dateFormat}`;
}

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 setState = async (newState) => {
  itemInfo.value.state = newState
  await updateTime()
}

</script>

<template>
  <UDashboardNavbar title="Zeiterfassung">

  </UDashboardNavbar>
  <UDashboardToolbar>
    <template #left>
      <UButton
          @click="startTime"
          :disabled="runningTimeInfo.id "
      >
        Start
      </UButton>
      <UButton
          @click="stopStartedTime"
          :disabled="!runningTimeInfo.id"
      >
        Stop
      </UButton>
      <UButton
          @click="configTimeMode = 'create'; itemInfo = {start: new Date(), end: new Date(), user: user.id}; showConfigTimeModal = true"
      >
        Erstellen
      </UButton>
      <USelectMenu
          :options="profileStore.profiles"
          option-attribute="fullName"
          value-attribute="id"
          v-model="filterUser"
      >
        <template #label>
          {{profileStore.getProfileById(filterUser) ? profileStore.getProfileById(filterUser).fullName : "Kein Benutzer ausgewählt"}}
        </template>
      </USelectMenu>
    </template>
  </UDashboardToolbar>
  <div v-if="runningTimeInfo.id" class="m-3">

    Start: {{dayjs(runningTimeInfo.start).format("DD.MM.YY HH:mm")}}

    <UFormGroup
        label="Notizen:"
    >
      <UTextarea
          v-model="runningTimeInfo.notes"
      />
    </UFormGroup>

    <UFormGroup
        label="Projekt:"
    >
      <USelectMenu
          :options="dataStore.projects"
          option-attribute="name"
          value-attribute="id"
          v-model="runningTimeInfo.projectId"
      >
        <template #label>
          {{ dataStore.projects.find(project => project.id === runningTimeInfo.projectId) ? dataStore.projects.find(project => project.id === runningTimeInfo.projectId).name : "Projekt auswählen" }}
        </template>
      </USelectMenu>
    </UFormGroup>


    <UFormGroup
        label="Kategorie:"
    >
      <USelectMenu
          v-model="runningTimeInfo.type"
          :options="timeTypes"
          option-attribute="label"
          value-attribute="label"
      >
        <template #label>
          {{runningTimeInfo.type ? runningTimeInfo.type : "Kategorie auswählen"}}
        </template>
      </USelectMenu>
    </UFormGroup>
  </div>

  <UModal
      v-model="showConfigTimeModal"
  >
    <UCard>
      <template #header>
        Zeiteintrag {{configTimeMode === 'create' ?  "erstellen" : "bearbeiten"}}
      </template>
      <UFormGroup
          label="Start:"
      >
        <VueDatePicker
            v-model="itemInfo.start"
            locale="de"
            cancel-text="Abbrechen"
            select-text="Auswählen"
            now-button-label="Jetzt"
            text-input="MM.dd.yyyy HH:mm"
            :dark="useColorMode().value !== 'light'"
            :format="format"
            :preview-format="format"
            :disabled="configTimeMode === 'create' ? false : itemInfo.state !== 'Entwurf'"
        />
      </UFormGroup>
      <UFormGroup
          label="Ende:"
      >
        <VueDatePicker
            v-model="itemInfo.end"
            locale="de"
            cancel-text="Abbrechen"
            select-text="Auswählen"
            now-button-label="Jetzt"
            text-input="MM.dd.yyyy HH:mm"
            :dark="useColorMode().value !== 'light'"
            :format="format"
            :preview-format="format"
            :disabled="configTimeMode === 'create' ? false : itemInfo.state !== 'Entwurf'"
        />
      </UFormGroup>
      <UFormGroup
          label="Benutzer:"
      >
        <USelectMenu
            :options="profileStore.profiles"
            v-model="itemInfo.user"
            option-attribute="fullName"
            value-attribute="id"
            :disabled="(configTimeMode === 'create' ? false : itemInfo.state !== 'Entwurf') || (!dataStore.hasRight('createTime') || !dataStore.hasRight('createOwnTime'))"
        >
          <template #label>
            {{profileStore.profiles.find(profile => profile.id === itemInfo.user) ? profileStore.profiles.find(profile => profile.id === itemInfo.user).fullName : "Benutzer auswählen"}}
          </template>
        </USelectMenu>
      </UFormGroup>
      <UFormGroup
          label="Projekt:"
      >
        <USelectMenu
            :options="dataStore.projects"
            v-model="itemInfo.projectId"
            option-attribute="name"
            value-attribute="id"
            searchable
            searchable-placeholder="Suche..."
            :search-attributes="['name']"
            :disabled="configTimeMode === 'create' ? false : itemInfo.state !== 'Entwurf'"
        >
          <template #label>
            {{dataStore.projects.find(project => project.id === itemInfo.projectId) ? dataStore.projects.find(project => project.id === itemInfo.projectId).name : "Projekt auswählen"}}
          </template>
        </USelectMenu>
      </UFormGroup>
      <UFormGroup
          label="Typ:"
      >
        <USelectMenu
            v-model="itemInfo.type"
            :options="timeTypes"
            option-attribute="label"
            value-attribute="label"
            :disabled="configTimeMode === 'create' ? false : itemInfo.state !== 'Entwurf'"
        >
          <template #label>
            {{itemInfo.type ? itemInfo.type : "Kategorie auswählen"}}
          </template>
        </USelectMenu>
      </UFormGroup>
      <UFormGroup
          label="Notizen:"
      >
        <UTextarea
            v-model="itemInfo.notes"
            :disabled="configTimeMode === 'create' ? false : itemInfo.state !== 'Entwurf'"
        />
      </UFormGroup>


      <template #footer v-if="configTimeMode === 'create' || itemInfo.state === 'Entwurf'">
        <InputGroup>
          <UButton
              @click="createTime"
              v-if="configTimeMode === 'create'"
          >
            Erstellen
          </UButton>
          <UButton
              @click="updateTime"
              v-else-if="configTimeMode === 'edit'"
              v-if="itemInfo.state === 'Entwurf'"
          >
            Speichern
          </UButton>
          <UButton
              @click="setState('Eingereicht')"
              v-if="itemInfo.state === 'Entwurf'"
          >
            Einreichen
          </UButton>
        </InputGroup>

      </template>
    </UCard>
  </UModal>

  <UTable
      class="mt-3"
      :columns="columns"
      :rows="filteredRows"
      :empty-state="{ icon: 'i-heroicons-circle-stack-20-solid', label: 'Noch keine Einträge' }"
      @select="(row) => {configTimeMode = 'edit';
        itemInfo = row;
        showConfigTimeModal = true}"
  >
    <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 #user-data="{row}">
      {{profileStore.profiles.find(profile => profile.id === row.user) ? profileStore.profiles.find(profile => profile.id === row.user).fullName : row.user }}
    </template>

    <template #start-data="{row}">
      {{dayjs(row.start).format("DD.MM.YY HH:mm")}}
    </template>
    <template #end-data="{row}">
      {{dayjs(row.end).format("DD.MM.YY HH:mm")}}
    </template>
    <template #duration-data="{row}">
      {{getDuration(row).composed}}
    </template>
    <template #projectId-data="{row}">
      {{dataStore.projects.find(project => project.id === row.projectId) ? dataStore.projects.find(project => project.id === row.projectId).name : ""}}
    </template>
  </UTable>
</template>

<style scoped>

</style>