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

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

//Store
const {customers, contracts } = storeToRefs(useDataStore())
const {fetchCustomers, getCustomerById, getContractById, fetchContracts} = useDataStore()

let currentContract = null



//Working
const mode = ref(route.params.mode || "show")
const itemInfo = ref({
  name: "",
  customer: 0,
  active: true
})

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

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



}

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

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

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

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

const updateCustomer = async () => {
  const {error} = await supabase
      .from("contracts")
      .update(itemInfo.value)
      .eq('id',itemInfo.value.id)
  console.log(error)
  mode.value = "show"
  itemInfo.value = {
    id: 0,
    name: "",
  }
  toast.add({title: "Vertrag erfolgreich gespeichert"})
  fetchContracts()
}



setupPage()
</script>

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

      Kundennummer: {{currentContract.customer}} <br>

      <UDivider
          class="my-2"
      />

      Beschreibung:<br>
      {{currentContract.description}}<br>




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



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

      <UFormGroup
          label="Name:"
      >
        <UInput
            v-model="itemInfo.name"
        />
      </UFormGroup>

      <UFormGroup
          label="Kunde:"
      >
        <USelectMenu
          v-model="itemInfo.customer"
          option-attribute="name"
          value-attribute="id"
          :options="customers"
          searchable
          :search-attributes="['name']"
        >
          <template #label>
            {{customers.find(customer => customer.id === itemInfo.customer) ? customers.find(customer => customer.id === itemInfo.customer).name : itemInfo.customer}}
          </template>
        </USelectMenu>
      </UFormGroup>

      <UFormGroup
          label="Vertrag aktiv:"
      >
        <UCheckbox
            v-model="itemInfo.active"
        />
      </UFormGroup>
      <UFormGroup
          label="Beschreibung:"
      >
        <UTextarea
            v-model="itemInfo.description"
        />
      </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>