<script setup>
import dayjs from "dayjs";

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 = ref(null)

/*watch(dataStore.tasks, (oldVal,newVal) => {
  console.log("OK")
  console.log(dataStore.tasks)
  currentItem.value = dataStore.getTaskById(Number(useRoute().params.id))
})*/

//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.value = dataStore.getTaskById(Number(useRoute().params.id))
  }

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

  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 editItem = async () => {
  router.push(`/tasks/edit/${currentItem.value.id}`)
  setupPage()
}

const cancelEditorCreate = () => {
  if(currentItem.value) {
    router.push(`/tasks/show/${currentItem.value.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.value.id}`)
  toast.add({title: "Aufgabe erfolgreich gespeichert"})
  dataStore.fetchTasks()
}



setupPage()
</script>

<template>
  <UDashboardPage>
    <UDashboardPanel grow>
      <UDashboardNavbar :title="currentItem ? currentItem.name : ''">
        <template #right>
          <UButton
              v-if="mode === 'edit'"
              @click="dataStore.updateItem('tasks',itemInfo)"
          >
            Speichern
          </UButton>
          <UButton
              v-else-if="mode === 'create'"
              @click="dataStore.createNewItem('tasks',itemInfo)"
          >
            Erstellen
          </UButton>
          <UButton
              @click="cancelEditorCreate"
              color="red"
              class="ml-2"
              v-if="mode === 'edit' || mode === 'create'"
          >
            Abbrechen
          </UButton>
          <UButton
              v-if="mode === 'show' && currentItem.id"
              @click="editItem"
          >
            Bearbeiten
          </UButton>
        </template>
      </UDashboardNavbar>

<!--      <UDashboardToolbar>
        <template #left>
          &lt;!&ndash;          <UButton @click="router.push(`/tasks/create`)">+ Aufgabe</UButton>

                    <UInput
                        v-model="searchString"
                        placeholder="Suche..."
                    />&ndash;&gt;

          <UCheckbox
              label="Erledigte Anzeigen"
              v-model="showDone"
          />
        </template>

        <template #right>
          <USelectMenu
              v-model="selectedColumns"
              icon="i-heroicons-adjustments-horizontal-solid"
              :options="templateColumns"
              multiple
              class="hidden lg:block"
          >
            <template #label>
              Spalten
            </template>
          </USelectMenu>
        </template>
      </UDashboardToolbar>-->


      <UTabs
          :items="[{label: 'Informationen'},{label: 'Logbuch'}]"
          v-if="currentItem && mode === 'show'"
          class="p-5"
      >
        <template #item="{item}">
          <UCard class="mt-5">
            <div v-if="item.label === 'Informationen'">


              <div class="truncate">
                <p>Kategorie: {{currentItem.categorie}}</p>
                <p v-if="currentItem.project">Projekt: <nuxt-link :to="`/projects/show/${currentItem.project}`">{{dataStore.getProjectById(currentItem.project).name}}</nuxt-link></p>
                <p>Beschreibung: {{currentItem.description}}</p>
              </div>

            </div>
            <!-- TODO: Logbuch Tasks -->
          </UCard>
        </template>
      </UTabs>

      <UForm v-else-if="mode === 'edit' || mode === 'create' " class="p-5">
        <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="Objekt:"
        >
          <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 : "Kein Objekt ausgewählt"}}
            </template>
          </USelectMenu>
        </UFormGroup>

        <UFormGroup
            label="Beschreibung:"
        >
          <UTextarea
              v-model="itemInfo.description"
          />
        </UFormGroup>
      </UForm>



    </UDashboardPanel>
  </UDashboardPage>

<!--  <h1
      class="mb-3 truncate font-bold text-2xl"
      v-if="currentItem"
  >Aufgabe: {{currentItem.name}}</h1>
  <UTabs
    :items="[{label: 'Informationen'},{label: 'Logbuch'}]"
    v-if="currentItem && mode === 'show'"
  >
    <template #item="{item}">
      <UCard class="mt-5">
        <div v-if="item.label === 'Informationen'">
          <Toolbar>
            <UButton
                v-if="mode === 'show' && currentItem.id"
                @click="editItem"
            >
              Bearbeiten
            </UButton>
            <UButton
                v-if="currentItem.project"
                @click="router.push(`/projects/show/${currentItem.project}`)"
            >
              Zum Projekt
            </UButton>
          </Toolbar>

          <div class="truncate">
            <p>Kategorie: {{currentItem.categorie}}</p>
            <p v-if="currentItem.project">Projekt: <nuxt-link :to="`/projects/show/${currentItem.project}`">{{dataStore.getProjectById(currentItem.project).name}}</nuxt-link></p>
            <p>Beschreibung: {{currentItem.description}}</p>
          </div>

        </div>
        &lt;!&ndash; TODO: Logbuch Tasks &ndash;&gt;
      </UCard>
    </template>
  </UTabs>
  <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="Objekt:"
    >
      <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 : "Kein Objekt ausgewählt"}}
        </template>
      </USelectMenu>
    </UFormGroup>




    <UFormGroup
        label="Beschreibung:"
    >
      <UTextarea
          v-model="itemInfo.description"
      />
    </UFormGroup>


    <template #footer>
      <UButton
          v-if="mode === 'edit'"
          @click="dataStore.updateItem('tasks',itemInfo)"
      >
        Speichern
      </UButton>
      <UButton
          v-else-if="mode === 'create'"
          @click="dataStore.createNewItem('tasks',itemInfo)"
      >
        Erstellen
      </UButton>
      <UButton
          @click="cancelEditorCreate"
          color="red"
          class="ml-2"
      >
        Abbrechen
      </UButton>
    </template>

  </UCard>-->
</template>

<style scoped>

</style>