<template>
  <main class="container mx-auto px-6 py-10">
    <div class="flex flex-col gap-2 mb-6 md:flex-row md:items-end md:justify-between">
      <div>
        <h1 class="text-3xl font-bold tracking-tight">Composants</h1>
        <p class="text-sm text-base-content/70">Catalogue et catégories de composants.</p>
      </div>
      <NuxtLink v-if="canEdit" :to="activeTab === 'categories' ? '/component-category/new' : '/component/create'" class="btn btn-primary btn-sm md:btn-md">
        {{ activeTab === 'categories' ? 'Ajouter une catégorie' : 'Ajouter un composant' }}
      </NuxtLink>
    </div>

    <EntityTabs v-model="activeTab" :tabs="pageTabs" aria-label="Composants">
      <template #tab-catalogue>
        <section class="card bg-base-100 shadow-sm">
          <div class="card-body space-y-4">
            <header class="flex flex-col gap-1">
              <h2 class="text-xl font-bold text-base-content tracking-tight">Composants créés</h2>
              <p class="text-sm text-base-content/50">
                Retrouvez ici tous les composants enregistrés, indépendamment de leur catégorie.
              </p>
            </header>

            <DataTable
              :columns="columns"
              :rows="componentRows"
              :loading="loadingComposants"
              :sort="table.sort.value"
              :pagination="paginationState"
              :column-filters="table.columnFilters.value"
              :show-per-page="true"
              empty-message="Aucun composant n'a encore été créé."
              no-results-message="Aucun composant ne correspond à votre recherche."
              @sort="table.handleSort"
              @update:current-page="table.handlePageChange"
              @update:per-page="table.handlePerPageChange"
              @update:column-filters="table.handleColumnFiltersChange"
            >
              <template #toolbar>
                <label class="w-full sm:w-72">
                  <span class="text-xs font-semibold uppercase tracking-wide text-base-content/70">Recherche</span>
                  <input
                    v-model="table.searchTerm.value"
                    type="text"
                    class="input input-bordered input-sm w-full mt-1"
                    placeholder="Nom ou référence…"
                    @input="table.debouncedSearch"
                  />
                </label>
              </template>

              <template #cell-preview="{ row }">
                <DocumentThumbnail
                  :document="resolvePrimaryDocument(row.component)"
                  :alt="resolvePreviewAlt(row.component)"
                />
              </template>

              <template #cell-name="{ row }">
                {{ row.component.name || 'Composant sans nom' }}
              </template>

              <template #cell-reference="{ row }">
                {{ row.component.reference || '—' }}
              </template>

              <template #cell-referenceAuto="{ row }">
                {{ row.component.referenceAuto || '—' }}
              </template>

              <template #cell-description="{ row }">
                <div v-if="row.component.description" class="group relative">
                  <span class="block cursor-help truncate">{{ row.component.description }}</span>
                  <div class="pointer-events-none invisible absolute left-0 top-full z-50 mt-1 max-w-sm overflow-hidden rounded-lg border border-base-300 bg-base-100 p-3 text-sm shadow-lg group-hover:pointer-events-auto group-hover:visible">
                    <p class="break-words whitespace-pre-wrap">{{ row.component.description }}</p>
                  </div>
                </div>
                <span v-else>—</span>
              </template>

              <template #cell-typeComposant="{ row }">
                <NuxtLink
                  v-if="row.component.typeComposant?.id"
                  :to="`/component-category/${row.component.typeComposant.id}/edit`"
                  class="link link-hover link-primary"
                >
                  {{ resolveComponentType(row.component) }}
                </NuxtLink>
                <span v-else>{{ resolveComponentType(row.component) }}</span>
              </template>

              <template #cell-createdAt="{ row }">
                <span class="whitespace-nowrap">{{ formatDate(row.component.createdAt) }}</span>
              </template>

              <template #cell-actions="{ row }">
                <div class="flex items-center justify-end gap-2">
                  <button
                    v-if="canEdit"
                    type="button"
                    class="btn btn-ghost btn-xs"
                    @click="navigateTo(`/component/${row.component.id}?edit=true`)"
                  >
                    Modifier
                  </button>
                  <button
                    v-if="canEdit"
                    type="button"
                    class="btn btn-ghost btn-xs text-error"
                    :disabled="loadingComposants"
                    @click="handleDeleteComponent(row.component)"
                  >
                    Supprimer
                  </button>
                  <NuxtLink
                    :to="`/component/${row.component.id}`"
                    class="btn btn-primary btn-xs"
                  >
                    Détails
                  </NuxtLink>
                </div>
              </template>
            </DataTable>
          </div>
        </section>
      </template>

      <template #tab-categories>
        <ManagementView
          category="COMPONENT"
          heading="Catégories de composant"
          :hide-heading="true"
        />
      </template>
    </EntityTabs>
  </main>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'
import DataTable from '~/components/common/DataTable.vue'
import ManagementView from '~/components/model-types/ManagementView.vue'
import { useComposants } from '~/composables/useComposants'
import { useComponentTypes } from '~/composables/useComponentTypes'
import { useDataTable } from '~/composables/useDataTable'
import DocumentThumbnail from '~/components/DocumentThumbnail.vue'
import { resolveDeleteImpact, buildDeleteMessage } from '~/shared/utils/deleteImpactUtils'
import { resolvePrimaryDocument, resolvePreviewAlt } from '~/shared/utils/catalogDisplayUtils'
import { formatFrenchDate } from '~/utils/date'

const route = useRoute()
const { canEdit } = usePermissions()

const activeTab = ref((route.query.tab as string) || 'catalogue')
watch(activeTab, (val) => {
  navigateTo({ query: { ...route.query, tab: val } }, { replace: true })
})

const pageTabs = computed(() => {
  const t: Array<{ key: string; label: string }> = [
    { key: 'catalogue', label: 'Catalogue' },
  ]
  if (canEdit.value) {
    t.push({ key: 'categories', label: 'Catégories' })
  }
  return t
})

const { composants, total, loadComposants, loading: loadingComposants, deleteComposant } = useComposants()
const { componentTypes, loadComponentTypes } = useComponentTypes()

const table = useDataTable(
  { fetchData: fetchComposants },
  { defaultSort: 'name', defaultDirection: 'asc', defaultPerPage: 20, persistToUrl: true, columnFilterKeys: ['typeComposant'] },
)

const columns = [
  { key: 'preview', label: 'Aperçu', width: 'w-24' },
  { key: 'name', label: 'Nom', sortable: true },
  { key: 'reference', label: 'Référence' },
  { key: 'referenceAuto', label: 'Réf. auto' },
  { key: 'description', label: 'Description' },
  { key: 'typeComposant', label: 'Type de composant', filterable: true, filterPlaceholder: 'Filtrer…' },
  { key: 'createdAt', label: 'Date', sortable: true },
  { key: 'actions', label: 'Actions' },
]

const composantsOnPage = computed(() => componentRows.value.length)
const paginationState = table.pagination(total, composantsOnPage)

const composantsList = computed(() => {
  return (composants.value || []).map((composant) => {
    const typeComposant = componentTypes.value.find(t => t.id === composant.typeComposantId)
    return { ...composant, typeComposant: typeComposant || composant.typeComposant || null }
  })
})

const componentRows = computed(() =>
  composantsList.value.map(component => ({
    id: component.id,
    component,
  })),
)

async function fetchComposants() {
  await loadComposants({
    search: table.searchTerm.value,
    page: table.currentPage.value,
    itemsPerPage: table.itemsPerPage.value,
    orderBy: table.sortField.value,
    orderDir: table.sortDirection.value as 'asc' | 'desc',
    typeName: table.columnFilters.value.typeComposant || undefined,
    force: true,
  })
}

const resolveComponentType = (component: Record<string, any>) => {
  if (component?.typeComposant?.name) return component.typeComposant.name
  if (component?.typeComposantLabel) return component.typeComposantLabel
  return '—'
}

const { confirm } = useConfirm()

const handleDeleteComponent = async (component: Record<string, any>) => {
  const componentName = component?.name || 'ce composant'
  const message = buildDeleteMessage(componentName, resolveDeleteImpact(component))
  const confirmed = await confirm({ title: 'Supprimer le composant', message, dangerous: true })
  if (!confirmed) return
  await deleteComposant(component.id)
  fetchComposants()
}

const formatDate = formatFrenchDate

onMounted(async () => {
  await Promise.all([fetchComposants(), loadComponentTypes()])
})
</script>
