<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 {jobs, customers} = storeToRefs(useDataStore())
const {fetchJobs, getJobById} = useDataStore()

let currentItem = null



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

})
const states = ["Offen", "In Bearbeitung", "Erledigt"]

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

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



}

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

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

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

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

const updateItem = async () => {
  const {error} = await supabase
      .from("jobs")
      .update(itemInfo.value)
      .eq('id',itemInfo.value.id)
  console.log(error)
  mode.value = "show"
  itemInfo.value = {
    id: 0,
    title: ""
  }
  toast.add({title: "Job erfolgreich gespeichert"})
  fetchJobs()
}



setupPage()
</script>

<template>
  <div>
    <UCard v-if="currentItem && mode == 'show'" >
      <template #header>
        <UBadge>
          {{currentItem.state}}
        </UBadge>

        {{currentItem.title}}
      </template>

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



      <!--      Kontakte:<br>
            &lt;!&ndash;        <ul>
            <li v-for="contact in currentCustomer.contacts.data">{{contact.lastName}}, {{contact.firstName}}</li>
          </ul>&ndash;&gt;
            &lt;!&ndash;        {{currentCustomer.contacts.data}}&ndash;&gt;
            <br>
            Projekte:<br>
            &lt;!&ndash;        <ul>
            <li v-for="project in currentCustomer.projects.data"><router-link :to="'/projects?id=' + project.id">{{project.name}}</router-link></li>
          </ul>&ndash;&gt;-->



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



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

      <UFormGroup
          label="Titel:"
      >
        <UInput
            v-model="itemInfo.title"
        />
      </UFormGroup>

      <UFormGroup
          label="Status:"
      >
        <USelectMenu
            v-model="itemInfo.state"
            :options="states"
        />
      </UFormGroup>

      <UFormGroup
          label="Kundennummer:"
      >
        <USelectMenu
            v-model="itemInfo.customer"
            :options="customers"
            option-attribute="name"
            value-attribute="id"
            searchable
            :search-attributes="['name']"
        >
          <template #label>
            {{customers.find(customer => customer.id === itemInfo.customer) ? customers.find(customer => customer.id === itemInfo.customer).name : "Kunde auswählen"}}
          </template>
        </USelectMenu>
      </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="createItem"
        >
          Erstellen
        </UButton>
        <UButton
            @click="cancelEditorCreate"
            color="red"
            class="ml-2"
        >
          Abbrechen
        </UButton>
      </template>

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

<style scoped>

</style>