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



definePageMeta({
  middleware: "auth"
})

defineShortcuts({
  'backspace': () => {
    router.push("/trackingTrips")
  },
  '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)


//Working
const mode = ref(route.params.mode || "show")
const itemInfo = ref({
  name: "",
  type: "Geschäftlich",
  driver: null,
  active: true
})
const oldItemInfo = ref({})

const profiles = ref([])
const projects = ref([])

//Functions
const setupPage = async () => {
  if(mode.value === "show" ){
    itemInfo.value = await useSupabaseSelectSingle("trackingtrips",route.params.id,"*, trackingDevice(*, vehicle(*))")
  } else if(mode.value === "edit") {
    itemInfo.value = await useSupabaseSelectSingle("trackingtrips",route.params.id,"*")

  }

  if(itemInfo.value) oldItemInfo.value = JSON.parse(JSON.stringify(itemInfo.value))

  profiles.value = await useSupabaseSelect("profiles","*")
  projects.value = await useSupabaseSelect("projects","*")
}

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

}



const getRowAmount = (row) => {
  let amount = 0

  row.accounts.forEach(account => {
    amount += account.amountNet
    amount += account.amountTax
  })

  return amount
}

setupPage()

const zoom = ref(6)

</script>

<template>
  <UDashboardNavbar
      :ui="{center: 'flex items-stretch gap-1.5 min-w-0'}"
  >
    <template #left>
      <UButton
          icon="i-heroicons-chevron-left"
          variant="outline"
          @click="router.push(`/trackingTrips`)"
      >
        Fahrten
      </UButton>
    </template>
    <template #center>
      <h1
          v-if="itemInfo"
          :class="['text-xl','font-medium' ]"
      ><UIcon name="i-heroicons-lock-closed" v-if="itemInfo.fixed"/><UIcon name="i-heroicons-lock-open" v-else/> {{itemInfo ? `Fahrt vom: ${dayjs(itemInfo.startTime).format("DD.MM.YY HH:mm")} über ${(itemInfo.distance/1000).toFixed(2)} km` : '' }}   </h1>
    </template>
    <template #right>
      <UButton
          @click="cancelEditorCreate"
          color="red"
          variant="outline"
          v-if="mode === 'edit' || mode === 'create'"
      >
        Abbrechen
      </UButton>
      <UButton
          v-if="mode === 'edit'"
          variant="outline"
          color="primary"
          icon="i-mdi-content-save"
          @click="dataStore.updateItem('trackingtrips',itemInfo, oldItemInfo)"
      >
         Entwurf
      </UButton>
      <UButton
          v-if="mode === 'edit'"
          icon="i-mdi-content-save"
          @click="dataStore.updateItem('trackingtrips',{...itemInfo, fixed:true}, oldItemInfo)"
      >
        Festschreiben
      </UButton>
      <UButton
          v-if="mode === 'show' && !itemInfo.fixed"
          @click="router.push(`/trackingTrips/edit/${itemInfo.id}`)"
      >
        Bearbeiten
      </UButton>
    </template>
  </UDashboardNavbar>



  <UTabs
      :items="[{label: 'Informationen'}]"
      v-if="mode === 'show' && itemInfo.id"
      class="p-5"
      v-model="openTab"
  >
    <template #item="{item}">
      <div v-if="item.label === 'Informationen'" class="flex flex-col mt-5">
        <div class="flex flex-row" style="height: 40vh">
          <div class="w-1/2 mr-5">
            <UCard>
              <table class="w-full">
                <tr>
                  <td>Festgeschrieben:</td>
                  <td>{{itemInfo.fixed ? "Ja" : "Nein"}}</td>
                </tr>
                <tr>
                  <td>Fahrzeug:</td>
                  <td><nuxt-link :to="`/vehicles/show/${itemInfo.trackingDevice.vehicle.id}`">{{itemInfo.trackingDevice.vehicle.licensePlate}}</nuxt-link></td>
                </tr>
                <tr>
                  <td>Typ:</td>
                  <td>{{itemInfo.type ? itemInfo.type : "-"}}</td>
                </tr>
                <tr>
                  <td>Fahrer:</td>
                  <td>{{profiles.find(i => i.id === itemInfo.driver) ? profiles.find(i => i.id === itemInfo.driver).fullName : "-"}}</td>
                </tr>
                <tr>
                  <td>Startzeit:</td>
                  <td>{{dayjs(itemInfo.startTime).format("DD.MM.YY HH:mm")}}</td>
                </tr>
                <tr>
                  <td>Endzeit:</td>
                  <td>{{dayjs(itemInfo.endTime).format("DD.MM.YY HH:mm")}}</td>
                </tr>
                <tr>
                  <td>Entfernung:</td>
                  <td>{{(itemInfo.distance/1000).toFixed(2)}} km</td>
                </tr>
                <tr>
                  <td>Beschreibung:</td>
                  <td>{{itemInfo.description ? itemInfo.description : "-" }}</td>
                </tr>
              </table>


            </UCard>
            <UCard class="mt-5">
              <Map :markers="[[itemInfo.startLatitude, itemInfo.startLongitude],[itemInfo.endLatitude, itemInfo.endLongitude]]"
                :startMarker="[itemInfo.startLatitude, itemInfo.startLongitude]"
                 :endMarker="[itemInfo.endLatitude, itemInfo.endLongitude]"
              />




            </UCard>
          </div>
          <div class="w-1/2">
            <UCard>
              <div style="height: 75vh">
                <HistoryDisplay
                    type="trackingtrip"
                    v-if="itemInfo"
                    :element-id="itemInfo.id"
                    render-headline
                />
              </div>

            </UCard>
          </div>
        </div>
        <div class="h-40 mt-5">


        </div>
      </div>
    </template>

  </UTabs>
  <UForm
      v-else-if="mode === 'edit' || mode === 'create'"
      class="p-5"
  >
    <UFormGroup
        label="Typ:"
    >
      <USelectMenu
          v-model="itemInfo.type"
          :options="['Privat','Geschäftlich','Arbeitsweg']"
      />
    </UFormGroup>
    <UFormGroup
        label="Fahrer:"
    >
      <USelectMenu
          v-model="itemInfo.driver"
          :options="[{id: null, fullName: 'Kein Fahrer'},...profiles]"
          option-attribute="fullName"
          value-attribute="id"

      >
        <template #label>
          {{profiles.find(profile => profile.id === itemInfo.driver) ? profiles.find(profile => profile.id === itemInfo.driver).fullName : 'Kein Fahrer ausgewählt'}}
        </template>
      </USelectMenu>
    </UFormGroup>
    <UFormGroup
        label="Projekt:"
    >
      <USelectMenu
          v-model="itemInfo.project"
          :options="projects"
          option-attribute="name"
          value-attribute="id"

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

  </UForm>
</template>

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