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




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


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

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

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

const platform = ref("default")

const projects = ref([])

const setup = async () => {
  times.value = await useSupabaseSelect("times","*, profile(*), project(id, name)")
  projects.value = await useSupabaseSelect("projects","*")



  runningTimeInfo.value = (await supabase
      .from("times")
      .select()
      .eq("tenant", profileStore.currentTenant)
      .eq("profile", profileStore.activeProfile.id)
      .is("endDate",null)
      .single()).data

}

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: "",
  notes: null,
  project: 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: "project",
    label: "Projekt",
  },
  {
    key: "notes",
    label: "Notizen",
  }
]





const startTime = async () => {
  console.log("started")
  timeInfo.value.profile = profileStore.activeProfile.id
  timeInfo.value.startDate = dayjs()
  timeInfo.value.tenant = profileStore.currentTenant

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

  if(error) {
    console.log(error)
    toast.add({title: "Fehler beim starten der Zeit",color:"rose"})
  } else if(data) {
    toast.add({title: "Zeit erfolgreich gestartet"})
    runningTimeInfo.value = data[0]
  }

}

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


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

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

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

const openTime = (row) => {
  itemInfo.value = row

  itemInfo.value.project = itemInfo.value.project.id
  itemInfo.value.profile = itemInfo.value.profile.id

  showConfigTimeModal.value = true
  configTimeMode.value = "edit"


}

const updateTime = async () => {
  let data = itemInfo.value

  data.profile = data.profile.id
  data.project = data.project.id

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

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

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

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

const getSecondInfo = (item) => {
  let returnArray = []

  if(item.type) returnArray.push(item.type)
  if(item.project) returnArray.push(item.project.name)
  if(item.notes) returnArray.push(item.notes)

  return returnArray
}

</script>

<template>
  <UDashboardNavbar title="Projektzeiten">
    <template #toggle>
      <div v-if="platform === 'mobile'"></div>
    </template>
  </UDashboardNavbar>
  <UDashboardToolbar>
    <template #left>
      <UButton
          @click="startTime"
          :disabled="runningTimeInfo "
      >
        Start
      </UButton>
      <UButton
          @click="stopStartedTime"
          :disabled="!runningTimeInfo"
      >
        Stop
      </UButton>
      <UButton
          v-if="platform !== 'mobile'"
          @click="configTimeMode = 'create'; itemInfo = {startDate: new Date(), endDate: new Date()}; showConfigTimeModal = true"
      >
        Erstellen
      </UButton>
      <USelectMenu
          v-if="platform !== 'mobile'"
          :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" class="m-3">

    Start: {{dayjs(runningTimeInfo.startDate).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.project"
      >
        <template #label>
          {{ dataStore.projects.find(project => project.id === runningTimeInfo.project) ? dataStore.projects.find(project => project.id === runningTimeInfo.project).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>
        Projektzeit {{configTimeMode === 'create' ?  "erstellen" : "bearbeiten"}}
      </template>
      <UFormGroup
          label="Start:"
      >
        <UPopover :popper="{ placement: 'bottom-start' }">
          <UButton
              icon="i-heroicons-calendar-days-20-solid"
              :label="itemInfo.startDate ? dayjs(itemInfo.startDate).format('DD.MM.YYYY HH:mm') : 'Datum auswählen'"
              variant="outline"
          />

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

          <template #panel="{ close }">
            <LazyDatePicker v-model="itemInfo.endDate" @close="close" mode="dateTime" />
          </template>
        </UPopover>
      </UFormGroup>
      <UFormGroup
          label="Benutzer:"
      >
        <USelectMenu
            :options="profileStore.profiles"
            v-model="itemInfo.profile"
            option-attribute="fullName"
            value-attribute="id"
        >
          <template #label>
            {{profileStore.profiles.find(profile => profile.id === itemInfo.profile) ? profileStore.profiles.find(profile => profile.id === itemInfo.profile).fullName : "Benutzer auswählen"}}
          </template>
        </USelectMenu>
      </UFormGroup>
      <UFormGroup
          label="Projekt:"
      >
        <USelectMenu
            :options="projects"
            v-model="itemInfo.project"
            option-attribute="name"
            value-attribute="id"
            searchable
            searchable-placeholder="Suche..."
            :search-attributes="['name']"
        >
          <template #label>
            {{dataStore.projects.find(project => project.id === itemInfo.project) ? dataStore.projects.find(project => project.id === itemInfo.project).name : "Projekt auswählen"}}
          </template>
        </USelectMenu>
      </UFormGroup>
      <UFormGroup
          label="Typ:"
      >
        <USelectMenu
            v-model="itemInfo.type"
            :options="timeTypes"
            option-attribute="label"
            value-attribute="label"
        >
          <template #label>
            {{itemInfo.type ? itemInfo.type : "Kategorie auswählen"}}
          </template>
        </USelectMenu>
      </UFormGroup>
      <UFormGroup
          label="Notizen:"
      >
        <UTextarea
            v-model="itemInfo.notes"
        />
      </UFormGroup>


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

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

  <UDashboardPanelContent class="w-full" v-if="platform === 'mobile'">
    <a
        v-for="item in filteredRows"
        class="my-1"
    >
      <p class="truncate text-left text-primary text-xl">{{dayjs(item.startDate).format("DD.MM.YYYY HH:mm")}} - {{dayjs(item.endDate).format("HH:mm")}}</p>
      <p class="text-sm">
        <span v-for="(i,index) in getSecondInfo(item)">
          {{i}}{{index < getSecondInfo(item).length - 1 ? " - " : ""}}
        </span>

      </p>
    </a>
  </UDashboardPanelContent>


  <UTable
      v-else
      class="mt-3"
      :columns="columns"
      :rows="filteredRows"
      :empty-state="{ icon: 'i-heroicons-circle-stack-20-solid', label: 'Noch keine Einträge' }"
      @select="(row) => openTime(row)"
  >
    <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}">
      {{row.profile ? row.profile.fullName : "" }}
    </template>

    <template #startDate-data="{row}">
      {{dayjs(row.startDate).format("DD.MM.YY HH:mm")}}
    </template>
    <template #endDate-data="{row}">
      {{dayjs(row.endDate).format("DD.MM.YY HH:mm")}}
    </template>
    <template #project-data="{row}">
      {{row.project ? row.project.name : "" }}
    </template>
  </UTable>
</template>

<style scoped>

</style>