<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: "",
  licensePlate: "",
  type: "",
  driver: null,
  active: true
})
const oldItemInfo = ref({})




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

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

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

}



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

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

  return amount
}

setupPage()
</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']"
      >{{itemInfo ? `Fahrt vom: ${dayjs(itemInfo.startTime).format("DD.MM.YY HH:mm")} über ${(itemInfo.distance/1000).toFixed(2)} km` : '' }}</h1>
    </template>
    <template #right>
      <UButton
          v-if="mode === 'edit'"
          @click="dataStore.updateItem('vehicles',itemInfo, oldItemInfo)"
      >
        Speichern
      </UButton>
    </template>
  </UDashboardNavbar>
  <UTabs
      :items="[{label: 'Informationen'},{label: 'Koordinaten'}]"
      v-if="mode === 'show' && itemInfo.id"
      class="p-5"
      v-model="openTab"
  >
    <template #item="{item}">
      <div v-if="item.label === 'Informationen'" class="flex flex-row mt-5">
        <div class="w-1/2 mr-2">
          <UCard>
            <table class="w-full">
              <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 : "Nicht gesetzt"}}</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>
            </table>


          </UCard>
        </div>
        <div class="w-1/2">
          <UCard>
<!--            <HistoryDisplay
                type="vehicle"
                v-if="itemInfo"
                :element-id="itemInfo.id"
                render-headline
            />-->
          </UCard>
        </div>
      </div>
      <div v-else-if="item.label === 'Koordinaten'">
        <UCard class="mt-5">
          <LMap
              style="height: 300px;"
              :center="[itemInfo.startLatitude, itemInfo.startLongitude]"
              :use-global-leaflet="false"
              :zoom="10"
          >
            <LTileLayer
                url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
                attribution="&amp;copy; <a href=&quot;https://www.openstreetmap.org/&quot;>OpenStreetMap</a> contributors"
                layer-type="base"
                name="OpenStreetMap"
            />
            <LMarker :lat-lng="[itemInfo.startLatitude, itemInfo.startLongitude]"  />
            <LMarker :lat-lng="[itemInfo.endLatitude, itemInfo.endLongitude]" />
          </LMap>
        </UCard>
      </div>
    </template>

  </UTabs>
  <UForm
      v-else-if="mode == 'edit' || mode == 'create'"
      class="p-5"
  >


  </UForm>
</template>

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