<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 )

//Store
const {customers, contracts } = storeToRefs(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 = dataStore.getContractById(Number(useRoute().params.id))
  }

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



}

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

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

const updateItem = async () => {
  const {error} = await supabase
      .from("contracts")
      .update(itemInfo.value)
      .eq('id',itemInfo.value.id)
  if(error) {
    console.log(error)
  }

  router.push(`/contracts/show/${currentContract.id}`)
  toast.add({title: "Vertrag erfolgreich gespeichert"})
  dataStore.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: {{dataStore.customers.find(customer => customer.id === currentContract.customer) ? dataStore.customers.find(customer => customer.id === currentContract.customer).name : ""}} <br>

      <UDivider
          class="my-2"
      />

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

      <DevOnly>
        {{currentContract}}
      </DevOnly>


      <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>
            {{dataStore.customers.find(customer => customer.id === itemInfo.customer) ? dataStore.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="updateItem"
        >
          Speichern
        </UButton>
        <UButton
            v-else-if="mode == 'create'"
            @click="dataStore.createNewItem('contracts',itemInfo)"
        >
          Erstellen
        </UButton>
        <UButton
            @click="cancelEditorCreate"
            color="red"
            class="ml-2"
        >
          Abbrechen
        </UButton>
      </template>

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

<style scoped>

</style>