<template>
  <div>
    <main class="container mx-auto px-6 py-8">
    <!-- Loading State -->
    <div v-if="d.loading.value" class="flex justify-center items-center py-16">
      <span class="loading loading-spinner loading-lg text-primary"></span>
    </div>

    <!-- Machine Details -->
    <div v-else-if="d.machine.value" ref="d.printAreaRef" class="space-y-8">
      <DocumentPreviewModal
        :document="d.previewDocument.value"
        :visible="d.previewVisible.value"
        :documents="d.machineDocumentsList.value"
        @close="d.closePreview"
      />

      <!-- Header with actions -->
      <MachineDetailHeader
        :title="machineViewTitle"
        :is-edit-mode="d.isEditMode.value"
        @toggle-edit="d.toggleEditMode"
        @open-print="d.openPrintModal"
      />

      <!-- Debug info -->
      <div v-if="d.debug.value" class="bg-yellow-100 p-4 rounded-lg">
        <p>Debug: Machine trouvée - {{ d.machine.value.name }}</p>
        <p>Components count: {{ d.components.value.length }}</p>
        <p>Pieces count: {{ d.pieces.value.length }}</p>
      </div>

      <!-- Hero -->
      <PageHero
        :title="d.machine.value.name"
        :subtitle="d.machine.value.description"
        min-height="min-h-[20vh]"
        max-width="max-w-md"
        rounded
      >
        <div class="flex justify-center gap-4">
          <div
            v-if="d.machine.value.site?.name"
            class="badge badge-outline font-semibold"
            :style="d.machine.value.site?.color ? { borderColor: d.machine.value.site.color + '60', backgroundColor: d.machine.value.site.color + '25', color: d.machine.value.site.color } : {}"
          >
            {{ d.machine.value.site?.name }}
          </div>
          <div v-if="d.machine.value.reference" class="badge badge-outline">
            {{ d.machine.value.reference }}
          </div>
        </div>
      </PageHero>

      <!-- Machine Info Card -->
      <MachineInfoCard
        ref="machineInfoCardRef"
        :is-edit-mode="d.isEditMode.value"
        :machine-name="d.machineName.value"
        :machine-reference="d.machineReference.value"
        :machine-site-id="d.machineSiteId.value"
        :machine-site-name="d.machine.value?.site?.name ?? ''"
        :sites="d.sites.value"
        :machine-constructeur-ids="d.machineConstructeurIds.value"
        :machine-constructeurs-display="d.machineConstructeursDisplay.value"
        :has-machine-constructeur="d.hasMachineConstructeur.value"
        :visible-custom-fields="d.visibleMachineCustomFields.value"
        :get-machine-field-id="d.getMachineFieldId"
        :machine-id="machineId"
        :machine-custom-field-defs="d.machine.value?.customFields ?? []"
        @update:machine-name="d.machineName.value = $event"
        @update:machine-reference="d.machineReference.value = $event"
        @update:machine-site-id="d.machineSiteId.value = $event"
        @update:constructeur-ids="d.handleMachineConstructeurChange"
        @set-custom-field-value="d.setMachineCustomFieldValue"
        @custom-fields-saved="() => { d.loadMachineData(); refreshVersions() }"
      />

      <!-- Documents -->
      <MachineDocumentsCard
        v-if="d.isEditMode.value || d.machineDocumentsList.value.length > 0"
        :documents="d.machineDocumentsList.value"
        :is-edit-mode="d.isEditMode.value"
        :uploading="d.machineDocumentsUploading.value"
        :files="d.machineDocumentFiles.value"
        @update:files="d.machineDocumentFiles.value = $event"
        @files-added="d.handleMachineFilesAdded"
        @preview="d.openPreview"
        @download="d.downloadDocument"
        @remove="d.removeMachineDocument"
      />

      <!-- Produits associés -->
      <MachineProductsCard
        v-if="d.isEditMode.value || d.machineDirectProducts.value.length > 0"
        :products="d.machineDirectProducts.value"
        :is-edit-mode="d.isEditMode.value"
        @add-product="openAddModal('product')"
        @remove-product="async (id) => { await d.removeProductLink(id); refreshVersions() }"
      />

      <!-- Components Section -->
      <MachineComponentsCard
        v-if="d.isEditMode.value || d.components.value.length > 0"
        :components="d.components.value"
        :is-edit-mode="d.isEditMode.value"
        :collapsed="d.componentsCollapsed.value"
        :collapse-toggle-token="d.collapseToggleToken.value"
        @toggle-collapse="d.toggleAllComponents"
        @update-component="d.updateComponent"
        @edit-piece="d.updatePieceFromComponent"
        @custom-field-update="d.updatePieceCustomField"
        @add-component="openAddModal('component')"
        @remove-component="async (id) => { await d.removeComponentLink(id); refreshVersions() }"
      />

      <!-- Machine Pieces Section -->
      <MachinePiecesCard
        v-if="d.isEditMode.value || d.machinePieces.value.length > 0"
        :pieces="d.machinePieces.value"
        :is-edit-mode="d.isEditMode.value"
        :collapsed="d.piecesCollapsed.value"
        :collapse-toggle-token="d.pieceCollapseToggleToken.value"
        @update-piece="d.updatePieceInfo"
        @edit-piece="d.editPiece"
        @custom-field-update="d.updatePieceCustomField"
        @add-piece="openAddModal('piece')"
        @remove-piece="async (id) => { await d.removePieceLink(id); refreshVersions() }"
        @toggle-collapse="d.toggleAllPieces"
      />

      <!-- Add Entity Modal -->
      <AddEntityToMachineModal
        :open="addModalOpen"
        :entity-kind="addModalKind"
        @close="addModalOpen = false"
        @confirm="handleAddEntity"
      />

      <!-- Save / Cancel buttons -->
      <div v-if="d.isEditMode.value" class="flex flex-col gap-3 md:flex-row md:justify-end">
        <button
          type="button"
          class="btn btn-ghost"
          :class="{ 'btn-disabled': d.saving.value }"
          @click="d.cancelEdition()"
        >
          Annuler
        </button>
        <button
          type="button"
          class="btn btn-primary"
          :disabled="!d.canSubmit.value"
          @click="submitMachineEdition"
        >
          <span v-if="d.saving.value" class="loading loading-spinner loading-sm mr-2" />
          Enregistrer les modifications
        </button>
      </div>

      <!-- Historique -->
      <EntityHistorySection
        :entries="history"
        :loading="historyLoading"
        :error="historyError"
        :field-labels="historyFieldLabels"
      />

      <!-- Versions -->
      <EntityVersionList
        ref="versionListRef"
        entity-type="machine"
        :entity-id="String(machineId)"
        :field-labels="historyFieldLabels"
        :refresh-key="versionRefreshKey"
        @restored="d.loadMachineData()"

      />

      <!-- Comments -->
      <div class="mt-4">
        <CommentSection
          entity-type="machine"
          :entity-id="String(machineId)"
          :entity-name="d.machine.value?.name"
          show-resolved
        />
      </div>
    </div>

    <!-- Error State -->
    <div v-else class="text-center py-12">
      <div class="max-w-md mx-auto">
        <div class="w-16 h-16 rounded-2xl bg-base-200 grid place-items-center mx-auto mb-5">
          <IconLucideAlertTriangle class="w-8 h-8 text-base-content/30" aria-hidden="true" />
        </div>
        <h3 class="text-lg font-semibold text-base-content mb-1">Machine non trouvée</h3>
        <p class="text-sm text-base-content/50 mb-6">La machine avec l'ID "{{ machineId }}" n'existe pas ou a été supprimée.</p>
        <NuxtLink to="/machines" class="btn btn-primary">
          Retour aux machines
        </NuxtLink>
      </div>
    </div>
    </main>

    <MachinePrintSelectionModal
      :open="d.printModalOpen.value"
      :selection="d.printSelection"
      :components="d.components.value"
      :pieces="d.machinePieces.value"
      @close="d.closePrintModal"
      @confirm="d.handlePrintConfirm"
      @select-all="d.setAllPrintSelection(true)"
      @deselect-all="d.setAllPrintSelection(false)"
    />
  </div>
</template>

<script setup>
import { computed, ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { useMachineDetailData } from '~/composables/useMachineDetailData'
import { useEntityHistory } from '~/composables/useEntityHistory'
import DocumentPreviewModal from '~/components/DocumentPreviewModal.vue'
import PageHero from '~/components/PageHero.vue'
import MachinePrintSelectionModal from '~/components/MachinePrintSelectionModal.vue'
import MachineDetailHeader from '~/components/machine/MachineDetailHeader.vue'
import MachineInfoCard from '~/components/machine/MachineInfoCard.vue'
import MachineDocumentsCard from '~/components/machine/MachineDocumentsCard.vue'
import MachineProductsCard from '~/components/machine/MachineProductsCard.vue'
import MachineComponentsCard from '~/components/machine/MachineComponentsCard.vue'
import MachinePiecesCard from '~/components/machine/MachinePiecesCard.vue'
import AddEntityToMachineModal from '~/components/machine/AddEntityToMachineModal.vue'
import EntityHistorySection from '~/components/common/EntityHistorySection.vue'
import EntityVersionList from '~/components/common/EntityVersionList.vue'
import IconLucideAlertTriangle from '~icons/lucide/alert-triangle'

const route = useRoute()
const machineId = route.params.id
const { canEdit } = usePermissions()

if (!machineId) {
  console.error('ID de machine manquant')
}

const d = useMachineDetailData(machineId)
const machineInfoCardRef = ref(null)
const versionRefreshKey = ref(0)
const refreshVersions = () => { versionRefreshKey.value++ }

const {
  history,
  loading: historyLoading,
  error: historyError,
  loadHistory,
} = useEntityHistory('machine')

const historyFieldLabels = {
  name: 'Nom',
  reference: 'Référence',
  prix: 'Prix',
  site: 'Site',
  constructeurIds: 'Fournisseurs',
  addedComponent: 'Composant ajouté',
  removedComponent: 'Composant supprimé',
  addedPiece: 'Pièce ajoutée',
  removedPiece: 'Pièce supprimée',
  addedProduct: 'Produit ajouté',
  removedProduct: 'Produit supprimé',
  componentLinks: 'Composants liés',
  pieceLinks: 'Pièces liées',
  productLinks: 'Produits liés',
}

const addModalOpen = ref(false)
const addModalKind = ref('component')

const openAddModal = (kind) => {
  addModalKind.value = kind
  addModalOpen.value = true
}

const handleAddEntity = async (entityId) => {
  if (addModalKind.value === 'component') {
    await d.addComponentLink(entityId)
  } else if (addModalKind.value === 'piece') {
    await d.addPieceLink(entityId)
  } else {
    await d.addProductLink(entityId)
  }
  refreshVersions()
}

const machineViewTitle = computed(() => {
  return d.isEditMode.value ? 'Modification de la machine' : 'Détails de la machine'
})

const submitMachineEdition = async () => {
  if (machineInfoCardRef.value?.saveFieldDefinitions) {
    await machineInfoCardRef.value.saveFieldDefinitions()
  }
  await d.submitEdition()
  refreshVersions()
}

onMounted(() => {
  d.loadMachineData()
  d.loadInitialData()
  loadHistory(String(machineId)).catch(() => {})

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