<script setup>
import HistoryDisplay from "~/components/HistoryDisplay.vue";
import dayjs from "dayjs";
import {useSupabaseSelectSingle} from "~/composables/useSupabase.js";

definePageMeta({
  middleware: "auth"
})

defineShortcuts({
  'backspace': () => {
    router.push("/checks")
  },
  'arrowleft': () => {
    if(openTab.value > 0){
      openTab.value -= 1
    }
  },
  'arrowright': () => {
    if(openTab.value < 3) {
      openTab.value += 1
    }
  },
})

const dataStore = useDataStore()
const route = useRoute()
const router = useRouter()
const toast = useToast()
const id = ref(route.params.id ? route.params.id : null )
const openTab = ref(0)

const vehicles = ref([])
const profiles = ref([])
const inventoryitems = ref([])


//Working
const mode = ref(route.params.mode || "show")
const itemInfo = ref({
  name: "",
  vehicle: null,
  inventoryitem: null,
  profile: null,
  distance: 1,
  distanceUnit: "days"
})

//Functions
const setupPage = async () => {

  profiles.value = await useSupabaseSelect("profiles")
  vehicles.value = await useSupabaseSelect("vehicles")
  inventoryitems.value = await useSupabaseSelect("inventoryitems")

  if(mode.value === "show" ){
    itemInfo.value = await useSupabaseSelectSingle("checks", route.params.id, "*, checkexecutions(*, executed_by(fullName)), vehicle(*), profile(*), inventoryitem(*)")
  } else if (mode.value === "edit"){
    itemInfo.value = await useSupabaseSelectSingle("checks", route.params.id, "*")
  }

  if(mode.value === "create") {
    let query = route.query

  }
}

const cancelEditorCreate = () => {
  if(itemInfo.value) {
    router.push(`/checks/show/${itemInfo.value.id}`)
  } else {
    router.push(`/checks/`)
  }
}

setupPage()
</script>

<template>
  <UDashboardNavbar>
    <template #left>
      <UButton
          icon="i-heroicons-chevron-left"
          variant="outline"
          @click="router.push(`/checks`)"
      >
        Überprüfungen
      </UButton>
    </template>
    <template #center>
      <h1
          v-if="itemInfo"
          :class="['text-xl','font-medium']"
      >{{itemInfo ? `Überprüfung: ${itemInfo.name}` : (mode === 'create' ? 'Überprüfung erstellen' : 'Überprüfung bearbeiten')}}</h1>
    </template>
    <template #right>
      <UButton
          v-if="mode === 'edit'"
          @click="dataStore.updateItem('checks',itemInfo)"
      >
        Speichern
      </UButton>
      <UButton
          v-else-if="mode === 'create'"
          @click="dataStore.createNewItem('checks',itemInfo)"
      >
        Erstellen
      </UButton>
      <UButton
          @click="cancelEditorCreate"
          color="red"
          class="ml-2"
          v-if="mode === 'edit' || mode === 'create'"
      >
        Abbrechen
      </UButton>
      <UButton
          v-if="mode === 'show'"
          @click="router.push(`/checks/edit/${itemInfo.id}`)"
      >
        Bearbeiten
      </UButton>
    </template>
  </UDashboardNavbar>
  <UDashboardPanelContent>
    <UTabs
        v-if="itemInfo.id && mode === 'show'"
        :items="[{label: 'Informationen'}, {label: 'Dokumente'}, {label: 'Ausführungen'}]"
        class="p-5"
        v-model="openTab"
    >
      <template #item="{item}">
        <div v-if="item.label === 'Informationen'" class="flex mt-5">
          <div class="w-1/2 mr-5">
            <UCard>
              <div class="text-wrap">
                <table class="mb-3 w-full">
                  <tr>
                    <td>Name:</td>
                    <td>{{itemInfo.name}}</td>
                  </tr>
                  <tr>
                    <td>Rhythmus:</td>
                    <td>
                      {{itemInfo.distance}}
                      <span v-if="itemInfo.distanceUnit === 'dayjs'">Tage</span>
                      <span v-if="itemInfo.distanceUnit === 'years'">Jahre</span>
                    </td>
                  </tr>
                  <tr v-if="itemInfo.vehicle">
                    <td>Fahrzeug:</td>
                    <td>{{itemInfo.vehicle.licensePlate}}</td>
                  </tr>
                  <tr v-if="itemInfo.profile">
                    <td>Person:</td>
                    <td>{{itemInfo.profile.fullName}}</td>
                  </tr>
                  <tr v-if="itemInfo.inventoryitem">
                    <td>Inventarartikel:</td>
                    <td>{{itemInfo.inventoryitem.name}}</td>
                  </tr>
                  <tr>
                    <td>Beschreibung:</td>
                    <td>{{itemInfo.description}}</td>
                  </tr>

                </table>

              </div>
            </UCard>
          </div>
          <div class="w-1/2">
            <UCard class="h-full">
              <HistoryDisplay
                  type="check"
                  v-if="itemInfo"
                  :element-id="itemInfo.id"
                  :render-headline="true"
              />
            </UCard>

          </div>
        </div>
        <div v-else-if="item.label === 'Dokumente'">
          <UCard class="mt-5">
            <Toolbar>
              <DocumentUpload
                  type="check"
                  :element-id="itemInfo.id"
              />
            </Toolbar>
            <DocumentList
                :documents="dataStore.getDocumentsByContractId(itemInfo.id)"
            />
          </UCard>

        </div>
        <div v-else-if="item.label === 'Ausführungen'">
          <UCard class="mt-5">
            <UTable
                :rows="itemInfo.checkexecutions"
                :columns="[{key:'created_at',label:'Ersellt am:'},{key:'executed_at',label:'Ausgeführt am:'},{key:'executed_by',label:'Ausgeführt von:'},{key:'description',label:'Beschreibung:'}]"
                class="w-full"
                :ui="{ divide: 'divide-gray-200 dark:divide-gray-800' }"
                :empty-state="{ icon: 'i-heroicons-circle-stack-20-solid', label: 'Keine Ausführungen anzuzeigen' }"
            >
              <template #created_at-data="{row}">
                {{dayjs(row.created_at).format("DD.MM.YYYY HH:mm")}}
              </template>
              <template #executed_at-data="{row}">
                {{dayjs(row.executed_at).format("DD.MM.YYYY HH:mm")}}
              </template>
              <template #executed_by-data="{row}">
                {{row.executed_by.fullName}}
              </template>
            </UTable>
          </UCard>
        </div>


      </template>
    </UTabs>
    <UForm v-else-if="mode === 'edit' || mode === 'create'" class="p-5" >
      <div class="mx-auto w-4/5">
        <div class="flex flex-row justify-around">
          <div class="w-1/2">
            <UDivider>Allgemeines</UDivider>
            <UFormGroup
                label="Name:"
            >
              <UInput
                  v-model="itemInfo.name"
              />
            </UFormGroup>
            <UFormGroup
                label="Typ:"
            >
              <UInput
                  v-model="itemInfo.type"
              />
            </UFormGroup>
            <UFormGroup
              label="Rhythmus"
              class="w-full"
            >
              <InputGroup class="w-full">
                <UInput
                  v-model="itemInfo.distance"
                  type="number"
                  class="flex-auto"
                ></UInput>
                <USelectMenu
                  :options="[{key: 'days', label: 'Tage'},{key:'years',label:'Jahre'}]"
                  option-attribute="label"
                  value-attribute="key"
                  v-model="itemInfo.distanceUnit"
                  class="w-40"
                ></USelectMenu>
              </InputGroup>
            </UFormGroup>


          </div>
          <div class=" ml-5 w-1/2">
            <UDivider>Verknüpftes Element</UDivider>
            <UFormGroup
                label="Fahrzeug:"
            >
              <USelectMenu
                  :options="vehicles"
                  option-attribute="licensePlate"
                  value-attribute="id"
                  v-model="itemInfo.vehicle"
                  :disabled="itemInfo.inventoryitem || itemInfo.profile"

              >

              </USelectMenu>
            </UFormGroup>
            <UFormGroup
                label="Person:"
            >
              <USelectMenu
                  :options="profiles"
                  option-attribute="fullName"
                  value-attribute="id"
                  v-model="itemInfo.profile"
                  :disabled="itemInfo.vehicle || itemInfo.inventoryitem"

              >

              </USelectMenu>
            </UFormGroup>
            <UFormGroup
                label="Inventarartikel:"
            >
              <USelectMenu
                  :options="inventoryitems"
                  option-attribute="name"
                  value-attribute="id"
                  v-model="itemInfo.inventoryitem"
                  :disabled="itemInfo.vehicle || itemInfo.profile"
              >

              </USelectMenu>
            </UFormGroup>

          </div>
        </div>
        <UFormGroup
            label="Beschreibung:"
        >
          <UTextarea
              v-model="itemInfo.description"
              rows="6"
              maxrows="12"
          />
        </UFormGroup>
      </div>





    </UForm>
  </UDashboardPanelContent>

</template>

<style scoped>
td {
  border-bottom: 1px solid lightgrey;
  vertical-align: top;
  padding-bottom: 0.15em;
  padding-top: 0.15em;
}
</style>