<template>
  <div>
    <DocumentPreviewModal
      :document="previewDocument"
      :visible="previewVisible"
      :documents="componentDocuments"
      @close="closePreview"
    />
    <DocumentEditModal
      :visible="editModalVisible"
      :document="editingDocument"
      @close="editModalVisible = false"
      @updated="handleDocumentUpdated"
    />
    <main class="container mx-auto px-6 py-10">
      <div v-if="loading" class="flex flex-col items-center gap-4 py-20 text-center">
        <span class="loading loading-spinner loading-lg" aria-hidden="true" />
        <p class="text-sm text-base-content/70">Chargement du composant…</p>
      </div>

      <EmptyState
        v-else-if="!component"
        title="Composant introuvable"
        description="Nous n'avons pas pu retrouver le composant demandé. Il a peut-être été supprimé."
        action-label="Retour au catalogue"
        action-to="/catalogues/composants"
      />

      <section v-else class="card border border-base-200 bg-base-100 shadow-sm max-w-5xl mx-auto">
        <div class="card-body space-y-6">
          <DetailHeader
            :title="isEditMode ? 'Modifier le composant' : component.name"
            :subtitle="isEditMode ? 'Ajustez les informations du composant et ses champs personnalisés.' : undefined"
            :is-edit-mode="isEditMode"
            :can-edit="canEdit"
            back-link="/catalogues/composants"
            @toggle-edit="isEditMode = !isEditMode"
          />

          <EntityTabs v-model="activeTab" :tabs="entityTabs" aria-label="Sections composant">
            <template #tab-general>
              <div class="space-y-6">
                <!-- Catégorie (always shown) -->
                <div class="grid grid-cols-1 gap-4 md:grid-cols-2">
                  <div class="form-control">
                    <label class="label">
                      <span class="label-text">Catégorie de composant</span>
                    </label>
                    <template v-if="isEditMode">
                      <div class="flex items-center gap-2">
                        <select
                          v-model="selectedTypeId"
                          class="select select-bordered select-sm md:select-md flex-1"
                          disabled
                        >
                          <option value="">Sélectionner une catégorie</option>
                          <option
                            v-for="type in componentTypeList"
                            :key="type.id"
                            :value="type.id"
                          >
                            {{ type.name }}
                          </option>
                        </select>
                        <NuxtLink
                          v-if="selectedTypeId"
                          :to="`/component-category/${selectedTypeId}/edit`"
                          class="btn btn-ghost btn-sm"
                          title="Voir la catégorie"
                        >
                          <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 20 20" fill="currentColor">
                            <path d="M11 3a1 1 0 100 2h2.586l-6.293 6.293a1 1 0 101.414 1.414L15 6.414V9a1 1 0 102 0V4a1 1 0 00-1-1h-5z" />
                            <path d="M5 5a2 2 0 00-2 2v8a2 2 0 002 2h8a2 2 0 002-2v-3a1 1 0 10-2 0v3H5V7h3a1 1 0 000-2H5z" />
                          </svg>
                        </NuxtLink>
                      </div>
                      <p class="text-xs text-base-content/60 mt-1">
                        La catégorie d'origine ne peut pas être modifiée depuis cette page.
                      </p>
                    </template>
                    <p v-else class="text-sm font-medium text-base-content py-1">
                      {{ selectedType?.name || '—' }}
                    </p>
                  </div>
                </div>

                <!-- Nom (always shown) -->
                <div class="grid grid-cols-1 gap-4 md:grid-cols-2">
                  <div class="form-control">
                    <label class="label">
                      <span class="label-text">Nom du composant</span>
                    </label>
                    <input
                      v-if="isEditMode"
                      v-model="editionForm.name"
                      type="text"
                      class="input input-bordered input-sm md:input-md"
                      :disabled="!canEdit || saving"
                      placeholder="Nom affiché dans le catalogue"
                      required
                    >
                    <p v-else class="text-sm font-medium text-base-content py-1">
                      {{ component.name }}
                    </p>
                  </div>
                </div>

                <!-- Description (if value or edit mode) -->
                <div v-if="isEditMode || component.description" class="form-control">
                  <label class="label">
                    <span class="label-text">Description</span>
                  </label>
                  <textarea
                    v-if="isEditMode"
                    v-model="editionForm.description"
                    class="textarea textarea-bordered textarea-sm md:textarea-md"
                    :disabled="!canEdit || saving"
                    placeholder="Description du composant (optionnel)"
                    rows="3"
                  />
                  <div v-else class="textarea textarea-bordered textarea-sm md:textarea-md bg-base-200">
                    {{ component.description }}
                  </div>
                </div>

                <!-- Référence auto (read-only, shown only if computed) -->
                <div v-if="component.referenceAuto" class="form-control">
                  <label class="label">
                    <span class="label-text">Référence auto</span>
                  </label>
                  <p class="text-sm font-medium text-base-content py-1 flex items-center gap-2">
                    <span class="font-mono font-semibold">{{ component.referenceAuto }}</span>
                    <span class="badge badge-sm badge-ghost">auto</span>
                  </p>
                </div>

                <!-- Référence + Fournisseurs (if value or edit mode) -->
                <div
                  v-if="isEditMode || component.reference || constructeurLinks.length"
                  class="grid grid-cols-1 gap-4 md:grid-cols-2"
                >
                  <div v-if="isEditMode || component.reference" class="form-control">
                    <label class="label">
                      <span class="label-text">Référence</span>
                    </label>
                    <input
                      v-if="isEditMode"
                      v-model="editionForm.reference"
                      type="text"
                      class="input input-bordered input-sm md:input-md"
                      :disabled="!canEdit || saving"
                      placeholder="Référence interne ou fournisseur"
                    >
                    <p v-else class="text-sm font-medium text-base-content py-1">
                      {{ component.reference }}
                    </p>
                  </div>

                  <div v-if="isEditMode || constructeurLinks.length" class="form-control">
                    <label class="label">
                      <span class="label-text">Fournisseur</span>
                    </label>
                    <ConstructeurSelect
                      v-if="isEditMode"
                      v-model="editionForm.constructeurIds"
                      class="w-full"
                      :disabled="!canEdit || saving"
                      placeholder="Rechercher un ou plusieurs fournisseurs..."
                      :initial-options="component?.constructeurs || []"
                    />
                  </div>
                </div>

                <!-- Constructeur links table -->
                <ConstructeurLinksTable
                  v-if="isEditMode && constructeurLinks.length"
                  v-model="constructeurLinks"
                />
                <ConstructeurLinksTable
                  v-else-if="!isEditMode && constructeurLinks.length"
                  :model-value="constructeurLinks"
                  :readonly="true"
                />

                <!-- Prix (if value or edit mode) -->
                <div v-if="isEditMode || component.prix" class="grid grid-cols-1 gap-4 md:grid-cols-2">
                  <div class="form-control">
                    <label class="label">
                      <span class="label-text">Prix indicatif (€)</span>
                    </label>
                    <input
                      v-if="isEditMode"
                      v-model="editionForm.prix"
                      type="number"
                      step="0.01"
                      min="0"
                      class="input input-bordered input-sm md:input-md"
                      :disabled="!canEdit || saving"
                      placeholder="Valeur indicatrice"
                    >
                    <p v-else class="text-sm font-medium text-base-content py-1">
                      {{ component.prix }} €
                    </p>
                  </div>
                </div>

                <UsedInSection entity-type="composants" :entity-id="component?.id ?? null" />
              </div>
            </template>

            <template #tab-structure>
              <div class="space-y-6">
                <!-- Skeleton preview (edit mode only) -->
                <StructureSkeletonPreview
                  v-if="isEditMode && selectedType"
                  :structure="selectedTypeStructure"
                  :description="selectedType.description || 'Ce squelette définit la structure et les contraintes du composant.'"
                  :preview-badge="formatStructurePreview(selectedTypeStructure)"
                  variant="component"
                  show-empty-state
                  :resolve-piece-label="resolvePieceLabel"
                  :resolve-product-label="resolveProductLabel"
                  :resolve-subcomponent-label="resolveSubcomponentLabel"
                />

                <!-- Skeleton slot selections -->
                <div
                  v-if="pieceSlotEntries.length || productSlotEntries.length || subcomponentSlotEntries.length"
                  class="space-y-3 rounded-lg border border-base-200 bg-base-200/30 p-4"
                >
                  <header class="space-y-1">
                    <h2 class="font-semibold text-base-content">{{ isEditMode ? 'Sélections du squelette' : 'Structure du composant' }}</h2>
                    <p class="text-xs text-base-content/70">
                      {{ isEditMode ? 'Choisissez les pièces, produits et sous-composants pour chaque emplacement requis par la catégorie.' : 'Pièces, produits et sous-composants associés à ce composant.' }}
                    </p>
                  </header>

                  <div v-if="pieceSlotEntries.length" class="space-y-2">
                    <h3 class="font-semibold text-sm text-base-content">Pièces</h3>
                    <div class="grid grid-cols-1 gap-3 md:grid-cols-2">
                      <div
                        v-for="slot in pieceSlotEntries"
                        :key="`piece-slot-${slot.slotId}`"
                        class="form-control"
                      >
                        <label class="label">
                          <span class="label-text text-xs font-medium" :class="{ 'text-error font-semibold': slot.isEmpty }">{{ slot.label }}</span>
                        </label>
                        <template v-if="isEditMode">
                          <div class="flex items-start gap-2">
                            <div class="flex-1">
                              <PieceSelect
                                :model-value="slot.selectedPieceId"
                                :disabled="!canEdit || saving"
                                :type-piece-id="slot.typePieceId"
                                @update:model-value="(value) => setPieceSlotSelection(slot.slotId, value)"
                              />
                            </div>
                            <div class="w-20 shrink-0">
                              <input
                                type="number"
                                :value="slot.quantity"
                                min="1"
                                class="input input-bordered input-sm w-full text-center"
                                :disabled="!canEdit || saving"
                                title="Quantité"
                                @change="(e) => setSlotQuantity(slot.slotId, Number((e.target as HTMLInputElement).value))"
                              >
                            </div>
                          </div>
                        </template>
                        <div v-else class="text-sm font-medium py-1 px-2 rounded" :class="slot.isEmpty ? 'border border-error bg-error/10 text-error font-semibold' : 'text-base-content'">
                          <template v-if="slot.isEmpty">{{ slot.label }} — manquant</template>
                          <template v-else>
                            {{ slot.selectedPieceName }}
                            <span v-if="slot.quantity > 1" class="badge badge-sm">x{{ slot.quantity }}</span>
                          </template>
                        </div>
                      </div>
                    </div>
                  </div>

                  <div v-if="productSlotEntries.length" class="space-y-2">
                    <h3 class="font-semibold text-sm text-base-content">Produits</h3>
                    <div class="grid grid-cols-1 gap-3 md:grid-cols-2">
                      <div
                        v-for="slot in productSlotEntries"
                        :key="`product-slot-${slot.slotId}`"
                        class="form-control"
                      >
                        <label class="label">
                          <span class="label-text text-xs font-medium" :class="{ 'text-error font-semibold': slot.isEmpty }">{{ slot.label }}</span>
                        </label>
                        <template v-if="isEditMode">
                          <ProductSelect
                            :model-value="slot.selectedProductId"
                            :disabled="!canEdit || saving"
                            :type-product-id="slot.typeProductId"
                            @update:model-value="(value) => setProductSlotSelection(slot.slotId, value)"
                          />
                        </template>
                        <div v-else class="text-sm font-medium py-1 px-2 rounded" :class="slot.isEmpty ? 'border border-error bg-error/10 text-error font-semibold' : 'text-base-content'">
                          <template v-if="slot.isEmpty">{{ slot.label }} — manquant</template>
                          <template v-else>{{ slot.selectedProductName }}</template>
                        </div>
                      </div>
                    </div>
                  </div>

                  <div v-if="subcomponentSlotEntries.length" class="space-y-2">
                    <h3 class="font-semibold text-sm text-base-content">Sous-composants</h3>
                    <div class="grid grid-cols-1 gap-3 md:grid-cols-2">
                      <div
                        v-for="slot in subcomponentSlotEntries"
                        :key="`sub-slot-${slot.slotId}`"
                        class="form-control"
                      >
                        <label class="label">
                          <span class="label-text text-xs font-medium" :class="{ 'text-error font-semibold': slot.isEmpty }">{{ slot.label }}</span>
                        </label>
                        <template v-if="isEditMode">
                          <ComposantSelect
                            :model-value="slot.selectedComponentId"
                            :disabled="!canEdit || saving"
                            :type-composant-id="slot.typeComposantId"
                            @update:model-value="(value) => setSubcomponentSlotSelection(slot.slotId, value)"
                          />
                        </template>
                        <div v-else class="text-sm font-medium py-1 px-2 rounded" :class="slot.isEmpty ? 'border border-error bg-error/10 text-error font-semibold' : 'text-base-content'">
                          <template v-if="slot.isEmpty">{{ slot.label }} — manquant</template>
                          <template v-else>{{ slot.selectedComponentName }}</template>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </template>

            <template #tab-documents>
              <!-- Documents -->
              <div
                v-if="isEditMode || componentDocuments.length > 0"
                class="space-y-4 rounded-lg border border-base-200 bg-base-200/40 p-4"
              >
                <header class="flex flex-col gap-1 md:flex-row md:items-center md:justify-between">
                  <div>
                    <h2 class="font-semibold text-base-content">Documents</h2>
                    <p class="text-xs text-base-content/70">
                      {{ isEditMode ? 'Gérez les documents associés à ce composant.' : 'Documents associés à ce composant.' }}
                    </p>
                  </div>
                  <span v-if="isEditMode && selectedFiles.length" class="badge badge-outline">
                    {{ selectedFiles.length }} document{{ selectedFiles.length > 1 ? 's' : '' }} prêt{{ selectedFiles.length > 1 ? 's' : '' }} à être ajouté{{ selectedFiles.length > 1 ? 's' : '' }}
                  </span>
                </header>
                <template v-if="isEditMode">
                  <div :class="{ 'pointer-events-none opacity-60': !canEdit || saving || uploadingDocuments }">
                    <DocumentUpload
                      v-model="selectedFiles"
                      title="Déposer vos fichiers"
                      subtitle="Formats acceptés : PDF, images, documents…"
                      @files-added="handleFilesAdded"
                    />
                  </div>
                  <p v-if="uploadingDocuments" class="text-xs text-base-content/70">
                    Téléversement des documents en cours…
                  </p>
                  <p v-else-if="loadingDocuments" class="text-xs text-base-content/70">
                    Chargement des documents en cours…
                  </p>
                  <DocumentListInline
                    v-else
                    :documents="componentDocuments"
                    :can-delete="canEdit"
                    :can-edit="true"
                    :delete-disabled="uploadingDocuments"
                    empty-text="Aucun document n'est associé à ce composant pour le moment."
                    @preview="openPreview"
                    @edit="openEditModal"
                    @delete="removeDocument"
                  />
                </template>
                <template v-else>
                  <p v-if="loadingDocuments" class="text-xs text-base-content/70">
                    Chargement des documents en cours…
                  </p>
                  <DocumentListInline
                    v-else
                    :documents="componentDocuments"
                    :can-delete="false"
                    :can-edit="false"
                    empty-text="Aucun document n'est associé à ce composant pour le moment."
                    @preview="openPreview"
                  />
                </template>
              </div>
            </template>

            <template #tab-custom-fields>
              <!-- Custom fields -->
              <div v-if="visibleCustomFields.length" class="space-y-4 rounded-lg border border-base-200 bg-base-200/40 p-4">
                <header class="space-y-1">
                  <h2 class="font-semibold text-base-content">Champs personnalisés</h2>
                  <p v-if="isEditMode" class="text-xs text-base-content/70">
                    Mettez à jour les valeurs propres à ce composant.
                  </p>
                </header>
                <template v-if="isEditMode">
                  <CustomFieldInputGrid :fields="customFieldInputs" :disabled="!canEdit || saving" />
                  <p v-if="hasRequiredCustomFields && !requiredCustomFieldsFilled" class="text-xs text-warning">
                    Certains champs personnalisés sont obligatoires. Veuillez les renseigner avant de valider.
                  </p>
                </template>
                <template v-else>
                  <div class="grid grid-cols-1 gap-4 md:grid-cols-2">
                    <div
                      v-for="field in visibleCustomFields"
                      :key="field.customFieldValueId || field.customFieldId || field.name"
                      class="form-control"
                    >
                      <label class="label">
                        <span class="label-text text-sm">{{ field.name }}</span>
                      </label>
                      <p class="text-sm font-medium text-base-content py-1">
                        {{ field.value }}
                      </p>
                    </div>
                  </div>
                </template>
              </div>
            </template>

            <template #tab-history>
              <div class="space-y-6">
                <EntityHistorySection
                  :entries="history"
                  :loading="historyLoading"
                  :error="historyError"
                  :field-labels="historyFieldLabels"
                />

                <EntityVersionList
                  entity-type="composant"
                  :entity-id="String(route.params.id)"
                  :field-labels="historyFieldLabels"
                  :refresh-key="versionRefreshKey"
                  @restored="fetchComponent()"
                />

                <!-- Comments -->
                <div class="mt-4">
                  <CommentSection
                    entity-type="composant"
                    :entity-id="String(route.params.id)"
                    :entity-name="component?.name"
                    show-resolved
                  />
                </div>
              </div>
            </template>
          </EntityTabs>

          <!-- Save/Cancel buttons (outside tabs) -->
          <div v-if="isEditMode" class="flex flex-col gap-3 md:flex-row md:justify-end">
            <button type="button" class="btn btn-ghost" :class="{ 'btn-disabled': saving }" @click="isEditMode = false">
              Annuler
            </button>
            <button type="button" class="btn btn-primary" :disabled="!canSubmit" @click="submitEdition">
              <span v-if="saving" class="loading loading-spinner loading-sm mr-2" />
              Enregistrer les modifications
            </button>
          </div>
          <p v-if="isEditMode && hasRequiredCustomFields && !requiredCustomFieldsFilled" class="text-xs text-error text-right">
            Merci de renseigner tous les champs personnalisés obligatoires.
          </p>
        </div>
      </section>
    </main>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'
import { useRoute } from '#imports'
import { useComponentEdit } from '~/composables/useComponentEdit'
import { useDocuments } from '~/composables/useDocuments'
import { usePermissions } from '~/composables/usePermissions'
import { useConstructeurs } from '~/composables/useConstructeurs'
import type { ConstructeurLinkEntry } from '~/shared/constructeurUtils'

const route = useRoute()
const { canEdit } = usePermissions()
const { getConstructeurById } = useConstructeurs()
const { updateDocument } = useDocuments()

const isEditMode = ref(false)
const versionRefreshKey = ref(0)

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

const {
  component,
  loading,
  saving,
  selectedFiles,
  uploadingDocuments,
  loadingDocuments,
  componentDocuments,
  previewDocument,
  previewVisible,
  selectedTypeId,
  editionForm,
  constructeurLinks,
  constructeurIdsFromForm,
  customFieldInputs,
  requiredCustomFieldsFilled,
  historyFieldLabels,
  canSubmit,
  componentTypeList,
  selectedType,
  selectedTypeStructure,
  pieceSlotEntries,
  productSlotEntries,
  subcomponentSlotEntries,
  history,
  historyLoading,
  historyError,
  openPreview,
  closePreview,
  removeDocument,
  handleFilesAdded,
  submitEdition: _submitEdition,
  fetchComponent,
  setSlotQuantity,
  setPieceSlotSelection,
  setProductSlotSelection,
  setSubcomponentSlotSelection,
  resolvePieceLabel,
  resolveProductLabel,
  resolveSubcomponentLabel,
  formatStructurePreview,
} = useComponentEdit(String(route.params.id))

const hasRequiredCustomFields = computed(() => customFieldInputs.value.some(f => f.required))

const submitEdition = async () => {
  await _submitEdition()
  if (!saving.value) {
    await fetchComponent()
    isEditMode.value = false
    versionRefreshKey.value++
  }
}

// Sync constructeurIds → constructeurLinks when IDs are added via ConstructeurSelect
watch(
  () => editionForm.constructeurIds,
  (ids) => {
    const currentIds = new Set(constructeurLinks.value.map(l => l.constructeurId))
    for (const id of ids) {
      if (!currentIds.has(id)) {
        const resolved = getConstructeurById(id)
        constructeurLinks.value.push({
          constructeurId: id,
          constructeur: resolved ? { id: resolved.id, name: resolved.name } : null,
          supplierReference: null,
        })
      }
    }
    // Remove links whose ID was removed from the select
    constructeurLinks.value = constructeurLinks.value.filter(l => ids.includes(l.constructeurId))
  },
)

const editingDocument = ref<any | null>(null)
const editModalVisible = ref(false)

const visibleCustomFields = computed(() => {
  if (isEditMode.value) return customFieldInputs.value
  return customFieldInputs.value.filter(
    (f) => f.value !== null && f.value !== undefined && f.value !== '',
  )
})

const entityTabs = computed(() => [
  { key: 'general', label: 'Général' },
  { key: 'structure', label: 'Structure', count: pieceSlotEntries.value.length + productSlotEntries.value.length + subcomponentSlotEntries.value.length },
  { key: 'documents', label: 'Documents', count: componentDocuments.value.length },
  { key: 'custom-fields', label: 'Champs perso', count: visibleCustomFields.value.length },
  { key: 'history', label: 'Historique' },
])

const openEditModal = (doc: any) => {
  editingDocument.value = doc
  editModalVisible.value = true
}

const handleDocumentUpdated = async (data: { name?: string; type?: string }) => {
  if (!editingDocument.value?.id) return
  const result = await updateDocument(editingDocument.value.id, data)
  if (result.success) {
    const idx = componentDocuments.value.findIndex((d: any) => d.id === editingDocument.value?.id)
    if (idx !== -1) {
      componentDocuments.value[idx] = { ...componentDocuments.value[idx], ...data }
    }
  }
  editModalVisible.value = false
  editingDocument.value = null
}

onMounted(() => {
  if (route.query.edit === 'true' && canEdit.value) {
    isEditMode.value = true
  }
})
</script>
