<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({})
const categories = ["Offen", "In Bearbeitung", "Dringed", "Erledigt"]

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

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

  if(mode.value === "create") {
    let query = route.query
    if(query.project) itemInfo.value.project = Number(query.project)
    if(query.plant) itemInfo.value.plant = Number(query.plant)

  }



}

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

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

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

const cancelEditorCreate = () => {
  if(currentItem) {
    router.push(`/tasks/show/${currentItem.id}`)
  } else {
    router.push(`/tasks/`)
  }
}

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

  if(error) {
    console.log(error)
  }


  router.push(`/tasks/show/${currentItem.id}`)
  toast.add({title: "Aufgabe erfolgreich gespeichert"})
  dataStore.fetchTasks()
}



setupPage()
</script>

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

        {{currentItem.name}}
      </template>

      {{currentItem}}<br>


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





      <template #footer>
        <UButton
            v-if="mode == 'show' && currentItem.id"
            @click="editItem"
        >
          Bearbeiten
        </UButton>
      </template>



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

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

      <UFormGroup
          label="Kategorie:"
      >
        <USelectMenu
            v-model="itemInfo.categorie"
            :options="categories"
        />
      </UFormGroup>

      <UFormGroup
          label="Benutzer:"
      >
        <USelectMenu
            v-model="itemInfo.user"
            :options="dataStore.profiles"
            option-attribute="fullName"
            value-attribute="id"
            searchable-placeholder="Suche..."
            searchable
            :search-attributes="['fullName']"
        >
          <template #label>
            {{dataStore.getProfileById(itemInfo.user) ? dataStore.getProfileById(itemInfo.user).fullName : "Kein Benutzer ausgewählt"}}
          </template>
        </USelectMenu>
      </UFormGroup>
      <UFormGroup
          label="Projekt:"
      >
        <USelectMenu
            v-model="itemInfo.project"
            :options="dataStore.projects"
            option-attribute="name"
            value-attribute="id"
            searchable-placeholder="Suche..."
            searchable
            :search-attributes="['name']"
        >
          <template #label>
            {{dataStore.getProjectById(itemInfo.project) ? dataStore.getProjectById(itemInfo.project).name : "Kein Projekt ausgewählt"}}
          </template>
        </USelectMenu>
      </UFormGroup>
      <UFormGroup
          label="Anlage:"
      >
        <USelectMenu
            v-model="itemInfo.plant"
            :options="dataStore.plants"
            option-attribute="name"
            value-attribute="id"
            searchable-placeholder="Suche..."
            searchable
            :search-attributes="['name']"
        >
          <template #label>
            {{dataStore.getPlantById(itemInfo.plant) ? dataStore.getPlantById(itemInfo.plant).name : "Keine Anlage ausgewählt"}}
          </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>