<script setup>
import HistoryDisplay from "~/components/HistoryDisplay.vue";
import DocumentList from "~/components/DocumentList.vue";
import DocumentUpload from "~/components/DocumentUpload.vue";
import Toolbar from "~/components/Toolbar.vue";

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 )



//Working
const mode = ref(route.params.mode || "show")
const itemInfo = ref({
  description: {
    html: ""
  }
})

const tabItems = [
  {
    label: "Informationen"
  },{
    label: "Projekte"
  },{
    label: "Aufgaben"
  },{
    label: "Dokumente"
  }
]

//Functions
const setupPage = async () => {
  if(mode.value === "show"){
    itemInfo.value = (await supabase.from("plants").select("*, customer(*)").eq("id",useRoute().params.id).single()).data
  } else if(mode.value === "edit") {
    itemInfo.value = (await supabase.from("plants").select().eq("id",useRoute().params.id).single()).data
  }

  if(mode.value === "create") {
    let query = route.query
    if(query.customer) itemInfo.value.customer = Number(query.customer)
  }
}

const contentChanged = (content) => {
  itemInfo.value.description.html = content.html
  itemInfo.value.description.text = content.text
  itemInfo.value.description.json = content.json
}

setupPage()
</script>

<template>
  <UDashboardNavbar :title="itemInfo ? itemInfo.name : (mode === 'create' ? 'Objekt erstellen' : 'Objekt bearbeiten')">
    <template #left>
      <UButton
          icon="i-heroicons-chevron-left"
          variant="outline"
          @click="router.push(`/plants`)"
      >
        Objekte
      </UButton>
    </template>
    <template #center>
      <h1
          v-if="itemInfo"
          :class="['text-xl','font-medium']"
      >{{itemInfo ? `Objekt: ${itemInfo.name}` : (mode === 'create' ? 'Objekt erstellen' : 'Objekt bearbeiten')}}</h1>
    </template>
    <template #right>
      <UButton
          v-if="mode === 'edit'"
          @click="dataStore.updateItem('plants',itemInfo)"
      >
        Speichern
      </UButton>
      <UButton
          v-else-if="mode === 'create'"
          @click="dataStore.createNewItem('plants',itemInfo)"
      >
        Erstellen
      </UButton>
      <UButton
          @click="router.push(itemInfo.id ? `/plants/show/${itemInfo.value.id}` : `/plants/`)"
          color="red"
          class="ml-2"
          v-if="mode === 'edit' || mode === 'create'"
      >
        Abbrechen
      </UButton>
      <UButton
          v-if="mode === 'show'"
          @click="router.push(`/plants/edit/${itemInfo.id}`)"
      >
        Bearbeiten
      </UButton>
    </template>
  </UDashboardNavbar>
  <UTabs
      :items="tabItems"
      v-if="mode === 'show'"
      class="p-5"
  >
    <template #item="{item}">
      <div v-if="item.label === 'Informationen'" class="flex flex-row mt-5">
        <UCard class="w-1/2 mr-5">
          <div class="text-wrap">
            <table>
              <tr>
                <td>Kunde:</td>
                <td><nuxt-link v-if="itemInfo.customer" :to="`/customers/show/${itemInfo.customer.id}`">{{itemInfo.customer.name}}</nuxt-link></td>
              </tr>
            </table>
          </div>
          <div v-if="itemInfo.description.html">
            <p>Notizen:</p>
            <span v-html="itemInfo.description.html"></span>
          </div>
        </UCard>
        <UCard class="w-1/2">
          <HistoryDisplay
              type="plant"
              v-if="itemInfo"
              :element-id="itemInfo.id"
              render-headline
          />
        </UCard>
      </div>
      <div v-else-if="item.label === 'Projekte'">
        <Toolbar>
          <UButton
              @click="router.push(`/projects/create?plant=${itemInfo.id}`)"
          >
            + Projekt
          </UButton>
        </Toolbar>

        <UTable
            :rows="dataStore.getProjectsByPlantId(itemInfo.id)"
            :columns="[{key: 'name', label: 'Name'}]"
            @select="(row) => router.push(`/projects/show/${row.id}`)"
            :empty-state="{ icon: 'i-heroicons-circle-stack-20-solid', label: 'Keine zugehörigen Projekte' }"
        >

        </UTable>

      </div>
      <div v-else-if="item.label === 'Aufgaben'">
        <Toolbar>
          <UButton
              @click="router.push(`/tasks/create?plant=${itemInfo.id}`)"
          >
            + Aufgabe
          </UButton>
        </Toolbar>
        <UTable
            :rows="dataStore.getTasksByPlantId(itemInfo.id)"
            :empty-state="{ icon: 'i-heroicons-circle-stack-20-solid', label: 'Keine zugehörigen Aufgaben' }"
            :columns="[{key: 'name', label: 'Name'},{key: 'categore', label: 'Kategorie'}]"
            @select="(row) => router.push(`/tasks/show/${row.id}`)"
        >

        </UTable>
      </div>
      <div v-else-if="item.label === 'Dokumente'" class="space-y-3">
        <Toolbar>
          <DocumentUpload
              type="plant"
              :element-id="itemInfo.id"
          />
        </Toolbar>

        <DocumentList :documents="dataStore.getDocumentsByPlantId(itemInfo.id)"/>

      </div>
    </template>
  </UTabs>


  <UForm
      v-else-if="mode === 'edit' || mode === 'create'"
      class="p-5"
  >
    <UFormGroup
        label="Name:"
    >
      <UInput
          v-model="itemInfo.name"
      />
    </UFormGroup>

    <UFormGroup
        label="Kundennummer:"
    >
      <USelectMenu
          v-model="itemInfo.customer"
          :options="dataStore.customers"
          option-attribute="name"
          value-attribute="id"
          searchable
          :search-attributes="['name']"
      >
        <template #label>
          {{dataStore.customers.find(customer => customer.id === itemInfo.customer) ? dataStore.customers.find(customer => customer.id === itemInfo.customer).name : "Kunde auswählen"}}
        </template>
      </USelectMenu>
    </UFormGroup>
    <UFormGroup
      label="Notizen:"
    >
      <Tiptap
          v-if="itemInfo.description"
          @updateContent="contentChanged"
          :preloadedContent="itemInfo.description.html"
      />
    </UFormGroup>

  </UForm>
</template>

<style scoped>

</style>