<script setup>
definePageMeta({
  middleware: "auth"
})

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

let currentItem = null



//Working
const mode = ref(route.params.mode || "show")
const itemInfo = ref({
  id: 0,
  name: "",
  licensePlate: "",
  type: "",
  driver: ""
})

//Functions
const setupPage = () => {
  if(mode.value === "show" || mode.value === "edit"){
    currentItem = dataStore.getVehicleById(Number(useRoute().params.id))
  }

  if(mode.value === "edit") itemInfo.value = currentItem



}

const createItem = async () => {
  const {data,error} = await supabase
      .from("vehicles")
      .insert([itemInfo.value])
      .select()

  if(error) {
    console.log(error)
  } else {
    mode.value = "show"
    itemInfo.value = {
      id: 0,
      name: ""
    }
    toast.add({title: "Fahrzeug erfolgreich erstellt"})
    await dataStore.fetchVehicles()
    router.push(`/vehicles/show/${data[0].id}`)
    setupPage()
  }
}

const editCustomer = async () => {
  router.push(`/vehicles/edit/${currentItem.id}`)
  setupPage()
}

const cancelEditorCreate = () => {
  mode.value = "show"
  itemInfo.value = {
    id: 0,
    name: "",
    licensePlate: "",
    type: ""
  }
}

const updateCustomer = async () => {
  const {error} = await supabase
      .from("vehicles")
      .update(itemInfo.value)
      .eq('id',itemInfo.value.id)
  if(error) {
    console.log(error)
  } else {
    mode.value = "show"
    itemInfo.value = {
      id: 0,
      name: "",
      licensePlate: "",
      type: ""
    }
    toast.add({title: "Fahrzeug erfolgreich gespeichert"})
    dataStore.fetchVehicles()
  }
}

setupPage()
</script>

<template>
  <div>
    <UCard v-if="currentItem && mode == 'show'" >
      <template #header>
        <UBadge
            v-if="currentItem.active"
        >
          Fahrzeug aktiv
        </UBadge>
        <UBadge
          v-else
          color="red"
        >
          Fahrzeug gesperrt
        </UBadge>
        {{currentItem.licensePlate}}
      </template>

      Typ: {{currentItem.type}} <br>
      Fahrer: {{dataStore.profiles.find(profile => profile.id === currentItem.driver) ? dataStore.profiles.find(profile => profile.id === currentItem.driver).fullName : 'Kein Fahrer gewählt'}} <br>



      <template #footer>
        <UButton
            v-if="mode == 'show' && currentItem.id"
            @click="editCustomer"
        >
          Bearbeiten
        </UButton>
        <UButton
            color="red"
            class="ml-2"
            disabled
        >
          Archivieren
        </UButton>
        <!-- TODO: Fahrzeug archivieren        -->
      </template>



    </UCard>
    <UCard v-else-if="mode == 'edit' || mode == 'create'" >
      <template #header v-if="mode === 'edit'">
        {{itemInfo.licensePlate}}
      </template>

      <UFormGroup
          label="Kennzeichen:"
      >
        <UInput
            v-model="itemInfo.licensePlate"
        />
      </UFormGroup>



      <UFormGroup
          label="Fahrzeug aktiv:"
      >
        <UCheckbox
            v-model="itemInfo.active"
        />
      </UFormGroup>
      <UFormGroup
          label="Typ:"
      >
        <UTextarea
            v-model="itemInfo.type"
        />
      </UFormGroup>
      <UFormGroup
          label="Fahrer:"
      >
        <USelectMenu
            v-model="itemInfo.driver"
            :options="dataStore.profiles"
            option-attribute="fullName"
            value-attribute="id"

        >
          <template #label>
            {{dataStore.profiles.find(profile => profile.id === itemInfo.driver) ? dataStore.profiles.find(profile => profile.id === itemInfo.driver).fullName : 'Kein Fahrer ausgewählt'}}
          </template>
        </USelectMenu>
      </UFormGroup>


      <template #footer>
        <UButton
            v-if="mode == 'edit'"
            @click="updateCustomer"
        >
          Speichern
        </UButton>
        <UButton
            v-else-if="mode == 'create'"
            @click="createItem"
        >
          Erstellen
        </UButton>
        <UButton
            @click="cancelEditorCreate"
            color="red"
            class="ml-2"
        >
          Abbrechen
        </UButton>
      </template>

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

<style scoped>

</style>