<template>
  <main class="container mx-auto px-6 py-8">
    

    <!-- Machines Management -->
    <div class="my-8">
      <!-- Header with Add Button -->
      <div class="flex justify-between items-center mb-6">
        <h2 class="text-2xl font-bold">Machines</h2>
        <button @click="showAddMachineModal = true" class="btn btn-primary">
          <IconLucidePlus class="w-5 h-5 mr-2" aria-hidden="true" />
          Ajouter une machine
        </button>
      </div>

      <!-- Filters -->
      <div class="card bg-base-100 shadow-lg mb-6">
        <div class="card-body">
          <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div class="form-control">
              <label class="label">
                <span class="label-text">Site</span>
              </label>
              <select v-model="selectedSite" class="select select-bordered">
                <option value="">Tous les sites</option>
                <option v-for="site in sites" :key="site.id" :value="site.id">
                  {{ site.name }}
                </option>
              </select>
            </div>
            <div class="form-control">
              <label class="label">
                <span class="label-text">Type de machine</span>
              </label>
              <select v-model="selectedType" class="select select-bordered">
                <option value="">Tous les types</option>
                <option v-for="type in machineTypes" :key="type.id" :value="type.id">
                  {{ type.name }}
                </option>
              </select>
            </div>
            <div class="form-control">
              <label class="label">
                <span class="label-text">Catégorie</span>
              </label>
              <select v-model="selectedCategory" class="select select-bordered">
                <option value="">Toutes les catégories</option>
                <option v-for="category in categories" :key="category" :value="category">
                  {{ category }}
                </option>
              </select>
            </div>
          </div>
        </div>
      </div>

      <!-- Machines Grid -->
      <div v-if="loading" class="flex justify-center items-center py-12">
        <span class="loading loading-spinner loading-lg"></span>
      </div>

      <div v-else-if="filteredMachines.length === 0" class="text-center py-12">
        <div class="max-w-md mx-auto">
          <IconLucideFactory class="w-16 h-16 mx-auto text-gray-400 mb-4" aria-hidden="true" />
          <h3 class="text-lg font-medium text-gray-900 mb-2">Aucune machine trouvée</h3>
          <p class="text-gray-500 mb-4">Commencez par ajouter votre première machine.</p>
          <button @click="showAddMachineModal = true" class="btn btn-primary">
            Ajouter une machine
          </button>
        </div>
      </div>

      <div v-else class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        <div 
          v-for="machine in filteredMachines" 
          :key="machine.id"
          class="card bg-base-100 shadow-lg hover:shadow-xl transition-shadow cursor-pointer"
          @click="viewMachineDetails(machine)"
        >
          <div class="card-body">
            <div class="flex items-center justify-between mb-2">
              <h3 class="card-title text-lg">{{ machine.name }}</h3>
              <div class="badge badge-primary badge-sm">{{ machine.typeMachine?.category || 'N/A' }}</div>
            </div>
            
            <p class="text-sm text-gray-600 mb-3">{{ machine.description || machine.typeMachine?.description }}</p>
            
            <div class="space-y-2 text-sm">
              <div class="flex items-center gap-2">
                <IconLucideMapPin class="w-4 h-4 text-blue-500" aria-hidden="true" />
                <span class="text-gray-600">{{ machine.site?.name || 'Site inconnu' }}</span>
              </div>
              
              <div class="flex items-center gap-2">
                <IconLucideSettings2 class="w-4 h-4 text-green-500" aria-hidden="true" />
                <span class="text-gray-600">{{ machine.typeMachine?.name || 'Type inconnu' }}</span>
              </div>
              
              <div v-if="machine.reference" class="flex items-center gap-2">
                <IconLucideTag class="w-4 h-4 text-orange-500" aria-hidden="true" />
                <span class="text-gray-600">{{ machine.reference }}</span>
              </div>
              
              <div v-if="machine.emplacement" class="flex items-center gap-2">
                <IconLucideBuilding class="w-4 h-4 text-purple-500" aria-hidden="true" />
                <span class="text-gray-600">{{ machine.emplacement }}</span>
              </div>
            </div>
            
            <div class="card-actions justify-end mt-4">
              <button class="btn btn-sm btn-outline" @click.stop="editMachine(machine)">
                Modifier
              </button>
              <button class="btn btn-sm btn-error" @click.stop="confirmDeleteMachine(machine)">
                Supprimer
              </button>
              <NuxtLink :to="`/machine/${machine.id}`" class="btn btn-sm btn-primary">
                Voir détails
              </NuxtLink>
            </div>
          </div>
        </div>
      </div>
</div>

<!-- Add Machine Modal -->
<div v-if="showAddMachineModal" class="modal modal-open">
      <div class="modal-box max-w-2xl">
        <h3 class="font-bold text-lg mb-4">Ajouter une nouvelle machine</h3>
        <form @submit.prevent="handleBaseMachineSubmit">
          <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
            <div class="form-control">
              <label class="label">
                <span class="label-text">Nom de la machine</span>
              </label>
              <input 
                id="machine-field-name"
                v-model="newMachine.name" 
                type="text" 
                placeholder="Ex: Presse hydraulique #1" 
                class="input input-bordered" 
                required
              />
            </div>
            
            <div class="form-control">
              <label class="label">
                <span class="label-text">Site</span>
              </label>
              <select id="machine-field-site" v-model="newMachine.siteId" class="select select-bordered" required>
                <option value="">Sélectionner un site</option>
                <option v-for="site in sites" :key="site.id" :value="site.id">
                  {{ site.name }}
                </option>
              </select>
  </div>
</div>

<!-- Create Component Model Modal -->
<div v-if="createComponentModelModal.open" class="modal modal-open">
  <div class="modal-box max-w-md">
    <h3 class="font-bold text-lg mb-1">Nouveau modèle de composant</h3>
    <p class="text-sm text-gray-500 mb-4">
      {{ createComponentModelModal.requirement?.label || createComponentModelModal.requirement?.typeComposant?.name || 'Famille de composants' }}
    </p>

    <form class="space-y-4" @submit.prevent="submitCreateComponentModel">
      <div class="form-control">
        <label class="label">
          <span class="label-text">Nom</span>
          <span class="label-text-alt text-error">*</span>
        </label>
        <input
          v-model="createComponentModelModal.name"
          type="text"
          class="input input-bordered input-sm"
          placeholder="Ex: Sangle 20 m"
          required
        />
      </div>

      <div class="form-control">
        <label class="label">
          <span class="label-text">Description</span>
          <span class="label-text-alt text-xs">Optionnel</span>
        </label>
        <textarea
          v-model="createComponentModelModal.description"
          class="textarea textarea-bordered textarea-sm"
          rows="3"
          placeholder="Notes sur ce modèle"
        ></textarea>
      </div>

      <div class="modal-action">
        <button type="button" class="btn btn-outline" @click="closeCreateComponentModelModal">Annuler</button>
        <button type="submit" class="btn btn-primary" :class="{ loading: createComponentModelModal.submitting }">
          Créer
        </button>
      </div>
    </form>
  </div>
</div>

<!-- Create Piece Model Modal -->
<div v-if="createPieceModelModal.open" class="modal modal-open">
  <div class="modal-box max-w-md">
    <h3 class="font-bold text-lg mb-1">Nouveau modèle de pièce</h3>
    <p class="text-sm text-gray-500 mb-4">
      {{ createPieceModelModal.requirement?.label || createPieceModelModal.requirement?.typePiece?.name || 'Groupe de pièces' }}
    </p>

    <form class="space-y-4" @submit.prevent="submitCreatePieceModel">
      <div class="form-control">
        <label class="label">
          <span class="label-text">Nom</span>
          <span class="label-text-alt text-error">*</span>
        </label>
        <input
          v-model="createPieceModelModal.name"
          type="text"
          class="input input-bordered input-sm"
          placeholder="Ex: Vis standard"
          required
        />
      </div>

      <div class="form-control">
        <label class="label">
          <span class="label-text">Description</span>
          <span class="label-text-alt text-xs">Optionnel</span>
        </label>
        <textarea
          v-model="createPieceModelModal.description"
          class="textarea textarea-bordered textarea-sm"
          rows="3"
          placeholder="Notes sur ce modèle"
        ></textarea>
      </div>

      <div class="modal-action">
        <button type="button" class="btn btn-outline" @click="closeCreatePieceModelModal">Annuler</button>
        <button type="submit" class="btn btn-primary" :class="{ loading: createPieceModelModal.submitting }">
          Créer
        </button>
      </div>
    </form>
  </div>
</div>

          <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
            <div class="form-control">
              <label class="label">
                <span class="label-text">Type de machine</span>
              </label>
              <select v-model="newMachine.typeMachineId" class="select select-bordered" required>
                <option value="">Sélectionner un type</option>
                <option v-for="type in machineTypes" :key="type.id" :value="type.id">
                  {{ type.name }} ({{ type.category }})
                </option>
              </select>
            </div>

            <div class="form-control">
              <label class="label">
                <span class="label-text">Référence</span>
              </label>
              <input 
                v-model="newMachine.reference" 
                type="text" 
                placeholder="Ex: PRESS-001" 
                class="input input-bordered"
              />
            </div>
          </div>

          <div class="form-control mb-4">
            <label class="label">
              <span class="label-text">Emplacement</span>
            </label>
            <input 
              v-model="newMachine.emplacement" 
              type="text" 
              placeholder="Ex: Atelier A, Zone 1" 
              class="input input-bordered"
            />
          </div>

          <!-- Type Preview -->
          <div v-if="selectedMachineType" class="mb-4 p-4 bg-gray-50 rounded-lg space-y-2 text-sm">
            <h4 class="font-semibold text-sm">Structure du type sélectionné :</h4>
            <div class="flex flex-wrap gap-3">
              <span class="inline-flex items-center gap-2">
                <span class="font-medium">Familles de composants :</span>
                <span class="badge badge-sm">{{ selectedMachineType.componentRequirements?.length || 0 }}</span>
              </span>
              <span class="inline-flex items-center gap-2">
                <span class="font-medium">Groupes de pièces :</span>
                <span class="badge badge-sm">{{ selectedMachineType.pieceRequirements?.length || 0 }}</span>
              </span>
              <span class="inline-flex items-center gap-2">
                <span class="font-medium">Catégorie :</span>
                <span class="badge badge-outline badge-sm">{{ selectedMachineType.category || 'N/A' }}</span>
              </span>
            </div>
            <p v-if="(selectedMachineType.componentRequirements?.length || 0) === 0 && (selectedMachineType.pieceRequirements?.length || 0) === 0" class="text-xs text-gray-500">
              Ce type n'a pas encore de familles configurées. La machine héritera de la structure legacy du type.
            </p>
          </div>

          <div v-if="selectedMachineType?.componentRequirements?.length" class="mb-6 space-y-4">
            <h4 class="text-sm font-semibold">Sélection des composants</h4>

            <div
              v-for="requirement in selectedMachineType.componentRequirements"
              :key="requirement.id"
              class="border border-base-200 rounded-lg p-4 space-y-3"
              :id="`component-group-${requirement.id}`"
            >
              <div class="flex flex-wrap items-start justify-between gap-3">
                <div>
                  <h5 class="font-medium text-sm">
                    {{ requirement.label || requirement.typeComposant?.name || 'Famille de composants' }}
                  </h5>
                  <p class="text-xs text-gray-500">
                    Type : {{ requirement.typeComposant?.name || 'Non défini' }} · Min : {{ requirement.minCount ?? (requirement.required ? 1 : 0) }}
                    · Max : {{ requirement.maxCount ?? '∞' }} ·
                    {{ requirement.allowNewModels ? 'Nouveaux modèles autorisés' : 'Modèles existants uniquement' }}
                  </p>
                </div>

                <div class="flex items-center gap-2">
                  <button
                    type="button"
                    class="btn btn-sm btn-outline"
                    @click="addComponentSelectionEntry(requirement)"
                    :disabled="requirement.maxCount !== null && getComponentRequirementEntries(requirement.id).length >= requirement.maxCount"
                  >
                    <IconLucidePlus class="w-4 h-4 mr-2" aria-hidden="true" />
                    Ajouter
                  </button>
                  <button
                    v-if="requirement.allowNewModels"
                    type="button"
                    class="btn btn-ghost btn-sm"
                    @click="openCreateComponentModelModal(requirement)"
                  >
                    Nouveau modèle
                  </button>
                </div>
              </div>

              <div v-if="getComponentRequirementEntries(requirement.id).length === 0" class="text-xs text-gray-500">
                Aucun composant sélectionné pour ce groupe.
              </div>

              <div
                v-for="(entry, entryIndex) in getComponentRequirementEntries(requirement.id)"
                :key="`${requirement.id}-${entryIndex}`"
                class="bg-base-200/60 rounded-md p-3 space-y-3"
              >
                <div class="flex flex-wrap items-center gap-2 text-xs">
                  <label class="inline-flex items-center gap-1">
                    <input
                      type="radio"
                      class="radio radio-xs"
                      :checked="entry.mode === 'model'"
                      @change="setComponentSelectionMode(requirement.id, entryIndex, 'model')"
                    />
                    Modèle existant
                  </label>
                  <label class="inline-flex items-center gap-1">
                    <input
                      type="radio"
                      class="radio radio-xs"
                      :checked="entry.mode === 'manual'"
                      @change="setComponentSelectionMode(requirement.id, entryIndex, 'manual')"
                      :disabled="!requirement.allowNewModels"
                    />
                    Définir manuellement
                  </label>
                </div>

                <div v-if="entry.mode === 'model'" class="grid grid-cols-1 md:grid-cols-2 gap-3">
                  <div class="form-control">
                    <label class="label">
                      <span class="label-text text-xs">Modèle de composant</span>
                    </label>
                    <select
                      class="select select-bordered select-sm"
                      :value="entry.componentModelId || ''"
                      @change="updateComponentSelectionEntry(requirement.id, entryIndex, { componentModelId: $event.target.value || '' })"
                    >
                      <option value="">Sélectionner un modèle</option>
                      <option
                        v-for="model in getComponentModelsForType(requirement.typeComposantId)"
                        :key="model.id"
                        :value="model.id"
                      >
                        {{ model.name }}
                      </option>
                    </select>
                    <p v-if="loadingComponentModels" class="text-[10px] text-gray-500 mt-1">Chargement des modèles...</p>
                    <p v-else-if="getComponentModelsForType(requirement.typeComposantId).length === 0" class="text-[10px] text-gray-500 mt-1">
                      Aucun modèle disponible pour ce type.
                    </p>
                  </div>
                </div>

                <div v-else class="grid grid-cols-1 md:grid-cols-2 gap-3">
                  <div class="form-control">
                    <label class="label">
                      <span class="label-text text-xs">Nom du composant</span>
                    </label>
                    <input
                      type="text"
                      class="input input-bordered input-sm"
                      :value="entry.name"
                      placeholder="Nom du composant"
                      @input="updateComponentSelectionEntry(requirement.id, entryIndex, { name: $event.target.value })"
                    />
                  </div>
                  <div class="form-control">
                    <label class="label">
                      <span class="label-text text-xs">Référence (optionnel)</span>
                    </label>
                    <input
                      type="text"
                      class="input input-bordered input-sm"
                      placeholder="(Non géré pour l'instant)"
                      disabled
                    />
                  </div>
                </div>

                <div class="flex justify-end">
                  <button
                    type="button"
                    class="btn btn-square btn-xs btn-error"
                    @click="removeComponentSelectionEntry(requirement.id, entryIndex)"
                  >
                    <IconLucideX class="w-4 h-4" aria-hidden="true" />
                  </button>
                </div>
              </div>
            </div>
          </div>

          <div v-if="selectedMachineType?.pieceRequirements?.length" class="mb-6 space-y-4">
            <h4 class="text-sm font-semibold">Sélection des pièces principales</h4>

            <div
              v-for="requirement in selectedMachineType.pieceRequirements"
              :key="requirement.id"
              class="border border-base-200 rounded-lg p-4 space-y-3"
              :id="`piece-group-${requirement.id}`"
            >
              <div class="flex flex-wrap items-start justify-between gap-3">
                <div>
                  <h5 class="font-medium text-sm">
                    {{ requirement.label || requirement.typePiece?.name || 'Groupe de pièces' }}
                  </h5>
                  <p class="text-xs text-gray-500">
                    Type : {{ requirement.typePiece?.name || 'Non défini' }} · Min : {{ requirement.minCount ?? (requirement.required ? 1 : 0) }}
                    · Max : {{ requirement.maxCount ?? '∞' }} ·
                    {{ requirement.allowNewModels ? 'Nouveaux modèles autorisés' : 'Modèles existants uniquement' }}
                  </p>
                </div>

                <div class="flex items-center gap-2">
                  <button
                    type="button"
                    class="btn btn-sm btn-outline"
                    @click="addPieceSelectionEntry(requirement)"
                    :disabled="requirement.maxCount !== null && getPieceRequirementEntries(requirement.id).length >= requirement.maxCount"
                  >
                    <IconLucidePlus class="w-4 h-4 mr-2" aria-hidden="true" />
                    Ajouter
                  </button>
                  <button
                    v-if="requirement.allowNewModels"
                    type="button"
                    class="btn btn-ghost btn-sm"
                    @click="openCreatePieceModelModal(requirement)"
                  >
                    Nouveau modèle
                  </button>
                </div>
              </div>

              <div v-if="getPieceRequirementEntries(requirement.id).length === 0" class="text-xs text-gray-500">
                Aucune pièce sélectionnée pour ce groupe.
              </div>

              <div
                v-for="(entry, entryIndex) in getPieceRequirementEntries(requirement.id)"
                :key="`${requirement.id}-piece-${entryIndex}`"
                class="bg-base-200/60 rounded-md p-3 space-y-3"
              >
                <div class="flex flex-wrap items-center gap-2 text-xs">
                  <label class="inline-flex items-center gap-1">
                    <input
                      type="radio"
                      class="radio radio-xs"
                      :checked="entry.mode === 'model'"
                      @change="setPieceSelectionMode(requirement.id, entryIndex, 'model')"
                    />
                    Modèle existant
                  </label>
                  <label class="inline-flex items-center gap-1">
                    <input
                      type="radio"
                      class="radio radio-xs"
                      :checked="entry.mode === 'manual'"
                      @change="setPieceSelectionMode(requirement.id, entryIndex, 'manual')"
                      :disabled="!requirement.allowNewModels"
                    />
                    Définir manuellement
                  </label>
                </div>

                <div v-if="entry.mode === 'model'" class="grid grid-cols-1 md:grid-cols-2 gap-3">
                  <div class="form-control">
                    <label class="label">
                      <span class="label-text text-xs">Modèle de pièce</span>
                    </label>
                    <select
                      class="select select-bordered select-sm"
                      :value="entry.pieceModelId || ''"
                      @change="updatePieceSelectionEntry(requirement.id, entryIndex, { pieceModelId: $event.target.value || '' })"
                    >
                      <option value="">Sélectionner un modèle</option>
                      <option
                        v-for="model in getPieceModelsForType(requirement.typePieceId)"
                        :key="model.id"
                        :value="model.id"
                      >
                        {{ model.name }}
                      </option>
                    </select>
                    <p v-if="loadingPieceModels" class="text-[10px] text-gray-500 mt-1">Chargement des modèles...</p>
                    <p v-else-if="getPieceModelsForType(requirement.typePieceId).length === 0" class="text-[10px] text-gray-500 mt-1">
                      Aucun modèle disponible pour ce type.
                    </p>
                  </div>
                </div>

                <div v-else class="grid grid-cols-1 md:grid-cols-2 gap-3">
                  <div class="form-control">
                    <label class="label">
                      <span class="label-text text-xs">Nom de la pièce</span>
                    </label>
                    <input
                      type="text"
                      class="input input-bordered input-sm"
                      :value="entry.name"
                      placeholder="Nom de la pièce"
                      @input="updatePieceSelectionEntry(requirement.id, entryIndex, { name: $event.target.value })"
                    />
                  </div>
                  <div class="form-control">
                    <label class="label">
                      <span class="label-text text-xs">Référence (optionnel)</span>
                    </label>
                    <input
                      type="text"
                      class="input input-bordered input-sm"
                      placeholder="(Non géré pour l'instant)"
                      disabled
                    />
                  </div>
                </div>

                <div class="flex justify-end">
                  <button
                    type="button"
                    class="btn btn-square btn-xs btn-error"
                    @click="removePieceSelectionEntry(requirement.id, entryIndex)"
                  >
                    <IconLucideX class="w-4 h-4" aria-hidden="true" />
                  </button>
                </div>
          </div>
        </div>
      </div>

      <div v-if="machinePreview" class="mb-6">
        <div class="border border-base-200 rounded-lg bg-base-100/80">
          <div class="p-4 space-y-4">
            <div class="flex items-center justify-between gap-3">
              <div class="flex items-center gap-2 text-sm font-semibold text-gray-700">
                <IconLucideEye class="w-4 h-4" aria-hidden="true" />
                <span>Prévisualisation avant création</span>
              </div>
              <span class="badge" :class="getStatusBadgeClass(machinePreview.status)">
                {{ machinePreview.status === 'ready' ? 'Prête à créer' : machinePreview.status === 'warning' ? 'À compléter' : 'Bloquante' }}
              </span>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
              <div
                v-for="field in machinePreview.base.fields"
                :key="field.key"
                class="flex flex-col gap-1"
              >
                <span class="text-[11px] uppercase tracking-wide text-gray-500">{{ field.label }}</span>
                <span
                  class="text-sm font-medium"
                  :class="field.status === 'missing'
                    ? 'text-error'
                    : field.status === 'optional'
                      ? 'text-gray-500 italic'
                      : 'text-gray-900'"
                >
                  {{ field.display }}
                </span>
              </div>
            </div>

            <div class="flex flex-wrap gap-2 text-xs text-gray-500">
              <span class="badge badge-ghost badge-sm">Type : {{ machinePreview.type.name }}</span>
              <span v-if="machinePreview.type.category" class="badge badge-ghost badge-sm">Catégorie : {{ machinePreview.type.category }}</span>
              <span class="badge badge-ghost badge-sm">Structure JSON : {{ machinePreview.type.hasStructuredDefinition ? 'Oui' : 'Legacy' }}</span>
            </div>

            <div v-if="machinePreview.base.issues.length" class="rounded-md bg-warning/10 border border-warning/30 p-3 text-xs text-warning">
              <p class="font-medium mb-1">Informations générales incomplètes :</p>
              <ul class="space-y-1">
                <li v-for="issue in machinePreview.base.issues" :key="issue.message">
                  <button
                    type="button"
                    class="flex w-full items-start gap-2 text-left hover:underline"
                    @click="handleIssueClick(issue)"
                  >
                    <span class="mt-0.5 text-[8px] leading-none">•</span>
                    <span>{{ issue.message }}</span>
                  </button>
                </li>
              </ul>
            </div>

            <div v-if="machinePreview.componentGroups.length" class="space-y-3">
              <h5 class="text-xs font-semibold uppercase tracking-wide text-gray-500">Composants hérités</h5>
              <div
                v-for="group in machinePreview.componentGroups"
                :key="group.id"
                class="border border-base-200 rounded-md p-3 space-y-3"
              >
                <div class="flex flex-wrap items-start justify-between gap-2">
                  <div>
                    <p class="text-sm font-semibold">{{ group.label }}</p>
                    <p class="text-xs text-gray-500">
                      Type : {{ group.typeName }} · Min {{ group.min }} ·
                      {{ group.max !== null ? `Max ${group.max}` : 'Max ∞' }}
                    </p>
                  </div>
                  <span class="badge badge-sm" :class="getStatusBadgeClass(group.status)">
                    {{ group.completed }} / {{ group.total || 0 }} complétée(s)
                  </span>
                </div>

                <div v-if="group.issues.length" class="rounded bg-warning/10 border border-warning/30 p-2 text-[11px] text-warning">
                  <ul class="list-disc pl-4 space-y-1">
                    <li v-for="issue in group.issues" :key="issue.message">{{ issue.message }}</li>
                  </ul>
                </div>

                <ul class="space-y-2">
                  <li
                    v-for="entry in group.entries"
                    :key="entry.key"
                    class="flex items-start gap-3"
                  >
                    <component
                      :is="entry.status === 'complete' ? IconLucideCheckCircle2 : IconLucideCircle"
                      class="w-4 h-4 mt-0.5"
                      :class="entry.status === 'complete' ? 'text-success' : 'text-gray-400'"
                      aria-hidden="true"
                    />
                    <div class="flex-1">
                      <p class="text-sm font-medium" :class="entry.status === 'complete' ? 'text-gray-900' : 'text-gray-500'">
                        {{ entry.title }}
                      </p>
                      <p v-if="entry.subtitle" class="text-xs text-gray-500">{{ entry.subtitle }}</p>
                    </div>
                    <span v-if="entry.mode === 'manual'" class="badge badge-ghost badge-xs">manuel</span>
                  </li>
                </ul>
              </div>
            </div>

            <div v-else class="text-xs text-gray-500">
              Aucun composant n'est requis pour ce type de machine.
            </div>

            <div v-if="machinePreview.pieceGroups.length" class="space-y-3">
              <h5 class="text-xs font-semibold uppercase tracking-wide text-gray-500">Pièces associées</h5>
              <div
                v-for="group in machinePreview.pieceGroups"
                :key="group.id"
                class="border border-base-200 rounded-md p-3 space-y-3"
              >
                <div class="flex flex-wrap items-start justify-between gap-2">
                  <div>
                    <p class="text-sm font-semibold">{{ group.label }}</p>
                    <p class="text-xs text-gray-500">
                      Type : {{ group.typeName }} · Min {{ group.min }} ·
                      {{ group.max !== null ? `Max ${group.max}` : 'Max ∞' }}
                    </p>
                  </div>
                  <span class="badge badge-sm" :class="getStatusBadgeClass(group.status)">
                    {{ group.completed }} / {{ group.total || 0 }} complétée(s)
                  </span>
                </div>

                <div v-if="group.issues.length" class="rounded bg-warning/10 border border-warning/30 p-2 text-[11px] text-warning">
                  <ul class="list-disc pl-4 space-y-1">
                    <li v-for="issue in group.issues" :key="issue.message">{{ issue.message }}</li>
                  </ul>
                </div>

                <ul class="space-y-2">
                  <li
                    v-for="entry in group.entries"
                    :key="entry.key"
                    class="flex items-start gap-3"
                  >
                    <component
                      :is="entry.status === 'complete' ? IconLucideCheckCircle2 : IconLucideCircle"
                      class="w-4 h-4 mt-0.5"
                      :class="entry.status === 'complete' ? 'text-success' : 'text-gray-400'"
                      aria-hidden="true"
                    />
                    <div class="flex-1">
                      <p class="text-sm font-medium" :class="entry.status === 'complete' ? 'text-gray-900' : 'text-gray-500'">
                        {{ entry.title }}
                      </p>
                      <p v-if="entry.subtitle" class="text-xs text-gray-500">{{ entry.subtitle }}</p>
                    </div>
                    <span v-if="entry.mode === 'manual'" class="badge badge-ghost badge-xs">manuel</span>
                  </li>
                </ul>
              </div>
            </div>

            <div v-else class="text-xs text-gray-500">
              Aucun groupe de pièces à configurer pour ce type.
            </div>

            <div v-if="machinePreview.issues.length && machinePreview.status !== 'ready'" class="rounded-md border border-warning/30 bg-warning/10 p-3 text-xs text-warning">
              <div class="flex items-start gap-2">
                <IconLucideAlertTriangle class="w-4 h-4 mt-0.5" aria-hidden="true" />
                <div class="space-y-1">
                  <p class="font-medium">Points à vérifier avant la création :</p>
                  <ul class="space-y-1">
                    <li v-for="issue in machinePreview.issues" :key="`${issue.scope}-${issue.message}`">
                      <button
                        type="button"
                        class="flex w-full items-start gap-2 text-left hover:underline"
                        @click="handleIssueClick(issue)"
                      >
                        <span class="mt-0.5 text-[8px] leading-none">•</span>
                        <span>
                          <span class="font-medium">{{ issue.scope }} :</span> {{ issue.message }}
                        </span>
                      </button>
                    </li>
                  </ul>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div v-if="blockingPreviewIssues.length" class="text-xs text-error bg-error/10 border border-error/20 rounded-md px-3 py-2 mb-4">
        Compléter les informations bloquantes avant de créer la machine.
      </div>

      <div class="modal-action">
        <button type="button" @click="closeCreateMachineModal" class="btn btn-outline">
          Annuler
        </button>
        <button type="submit" class="btn btn-primary" :disabled="!canCreateMachine">
          Créer la machine
        </button>
      </div>
        </form>
      </div>
    </div>
  </main>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { useMachines } from '~/composables/useMachines'
import { useSites } from '~/composables/useSites'
import { useMachineTypesApi } from '~/composables/useMachineTypesApi'
import { useComponentModels } from '~/composables/useComponentModels'
import { usePieceModels } from '~/composables/usePieceModels'
import { useToast } from '~/composables/useToast'
import IconLucidePlus from '~icons/lucide/plus'
import IconLucideFactory from '~icons/lucide/factory'
import IconLucideMapPin from '~icons/lucide/map-pin'
import IconLucideSettings2 from '~icons/lucide/settings-2'
import IconLucideTag from '~icons/lucide/tag'
import IconLucideBuilding from '~icons/lucide/building'
import IconLucideX from '~icons/lucide/x'
import IconLucideEye from '~icons/lucide/eye'
import IconLucideAlertTriangle from '~icons/lucide/alert-triangle'
import IconLucideCheckCircle2 from '~icons/lucide/check-circle-2'
import IconLucideCircle from '~icons/lucide/circle'

const { machines, loading, loadMachines, createMachine, createMachineFromType, deleteMachine } = useMachines()
const { sites, loadSites } = useSites()
const { machineTypes, loadMachineTypes } = useMachineTypesApi()
const { loadComponentModels, getComponentModelsForType, loadingComponentModels } = useComponentModels()
const { loadPieceModels, getPieceModelsForType, loadingPieceModels } = usePieceModels()
const route = useRoute()
const toast = useToast()

// Data
const showAddMachineModal = ref(false)
const selectedSite = ref('')
const selectedType = ref('')
const selectedCategory = ref('')

const newMachine = reactive({
  name: '',
  siteId: '',
  typeMachineId: '',
  reference: '',
  emplacement: ''
})

const componentRequirementSelections = reactive({})
const pieceRequirementSelections = reactive({})

const createComponentModelModal = reactive({
  open: false,
  requirement: null,
  requirementId: null,
  entryIndex: null,
  name: '',
  description: '',
  submitting: false,
})

const createPieceModelModal = reactive({
  open: false,
  requirement: null,
  requirementId: null,
  entryIndex: null,
  name: '',
  description: '',
  submitting: false,
})
const machineConfigurationVisible = ref(false)

// Computed
const selectedMachineType = computed(() => {
  if (!newMachine.typeMachineId) return null
  return machineTypes.value.find(type => type.id === newMachine.typeMachineId)
})

const categories = computed(() => {
  const cats = new Set()
  machineTypes.value.forEach(type => {
    if (type.category) cats.add(type.category)
  })
  return Array.from(cats)
})

const filteredMachines = computed(() => {
  let filtered = machines.value

  if (selectedSite.value) {
    filtered = filtered.filter(machine => machine.siteId === selectedSite.value)
  }

  if (selectedType.value) {
    filtered = filtered.filter(machine => machine.typeMachineId === selectedType.value)
  }

  if (selectedCategory.value) {
    filtered = filtered.filter(machine => machine.typeMachine?.category === selectedCategory.value)
  }

  return filtered
})

const getStatusBadgeClass = (status) => {
  if (status === 'ready') {
    return 'badge-success'
  }
  if (status === 'warning') {
    return 'badge-warning'
  }
  return 'badge-error'
}

const machinePreview = computed(() => {
  const type = selectedMachineType.value
  if (!type) {
    return null
  }

  const trimmedName = (newMachine.name || '').trim()
  const currentSite = newMachine.siteId
    ? sites.value.find((site) => site.id === newMachine.siteId) || null
    : null
  const trimmedReference = (newMachine.reference || '').trim()
  const trimmedEmplacement = (newMachine.emplacement || '').trim()

  const baseFields = [
    {
      key: 'name',
      label: 'Nom',
      display: trimmedName || 'À renseigner',
      status: trimmedName ? 'complete' : 'missing',
    },
    {
      key: 'site',
      label: 'Site',
      display: currentSite?.name || 'Sélectionner un site',
      status: currentSite ? 'complete' : 'missing',
    },
    {
      key: 'type',
      label: 'Type sélectionné',
      display: type.name,
      status: 'complete',
    },
    {
      key: 'reference',
      label: 'Référence',
      display: trimmedReference || 'Non renseignée',
      status: trimmedReference ? 'complete' : 'optional',
    },
    {
      key: 'emplacement',
      label: 'Emplacement',
      display: trimmedEmplacement || 'Non renseigné',
      status: trimmedEmplacement ? 'complete' : 'optional',
    },
  ]

  const baseIssues = []
  if (!trimmedName) {
    baseIssues.push({ message: 'Renseigner un nom de machine.', kind: 'error', anchor: 'machine-field-name' })
  }
  if (!currentSite) {
    baseIssues.push({ message: "Sélectionner un site d'affectation.", kind: 'error', anchor: 'machine-field-site' })
  }
  const baseStatus = baseIssues.some((issue) => issue.kind === 'error') ? 'error' : 'ready'

  const resolveComponentModel = (requirement, modelId) => {
    if (!modelId) {
      return null
    }
    return (getComponentModelsForType(requirement.typeComposantId) || []).find((model) => model.id === modelId) || null
  }

  const resolvePieceModel = (requirement, modelId) => {
    if (!modelId) {
      return null
    }
    return (getPieceModelsForType(requirement.typePieceId) || []).find((model) => model.id === modelId) || null
  }

  const componentGroups = (type.componentRequirements || []).map((requirement) => {
    const entriesSource = getComponentRequirementEntries(requirement.id)
    const entriesList = entriesSource ? [...entriesSource] : []
    const normalizedEntries = entriesList.map((entry, index) => {
      if (entry.mode === 'model') {
        const model = resolveComponentModel(requirement, entry.componentModelId)
        return {
          key: `${requirement.id}-${index}`,
          mode: 'model',
          status: model ? 'complete' : 'pending',
          title: model ? model.name : 'Sélectionner un modèle',
          subtitle: model?.description || null,
        }
      }
      const manualName = (entry.name || '').trim()
      return {
        key: `${requirement.id}-${index}`,
        mode: 'manual',
        status: manualName ? 'complete' : 'pending',
        title: manualName || 'Nom à renseigner',
        subtitle: manualName ? null : null,
      }
    })

    const min = requirement.minCount ?? (requirement.required ? 1 : 0)
    const max = requirement.maxCount ?? null
    const completed = normalizedEntries.filter((entry) => entry.status === 'complete').length
    const issues = []

    if (completed < min) {
      issues.push({ message: `Minimum ${min} sélection(s) requise(s)`, kind: 'error', anchor: `component-group-${requirement.id}` })
    }

    if (max !== null && completed > max) {
      issues.push({ message: `Maximum ${max} dépassé`, kind: 'error', anchor: `component-group-${requirement.id}` })
    }

    if (!requirement.allowNewModels && normalizedEntries.some((entry) => entry.mode === 'manual' && entry.status === 'complete')) {
      issues.push({ message: "Ce groupe n'autorise que les modèles existants.", kind: 'error', anchor: `component-group-${requirement.id}` })
    }

    if (normalizedEntries.some((entry) => entry.status !== 'complete')) {
        issues.push({ message: 'Compléter les sélections restantes.', kind: 'warning', anchor: `component-group-${requirement.id}` })
    }

    const status = issues.some((issue) => issue.kind === 'error')
      ? 'error'
      : issues.length > 0
        ? 'warning'
        : 'ready'

    return {
      id: requirement.id,
      label: requirement.label || requirement.typeComposant?.name || 'Famille de composants',
      typeName: requirement.typeComposant?.name || 'Non défini',
      min,
      max,
      entries: normalizedEntries,
      issues,
      completed,
      total: normalizedEntries.length,
      status,
    }
  })

  const pieceGroups = (type.pieceRequirements || []).map((requirement) => {
    const entriesSource = getPieceRequirementEntries(requirement.id)
    const entriesList = entriesSource ? [...entriesSource] : []
    const normalizedEntries = entriesList.map((entry, index) => {
      if (entry.mode === 'model') {
        const model = resolvePieceModel(requirement, entry.pieceModelId)
        return {
          key: `${requirement.id}-${index}`,
          mode: 'model',
          status: model ? 'complete' : 'pending',
          title: model ? model.name : 'Sélectionner un modèle',
          subtitle: model?.description || null,
        }
      }
      const manualName = (entry.name || '').trim()
      return {
        key: `${requirement.id}-${index}`,
        mode: 'manual',
        status: manualName ? 'complete' : 'pending',
        title: manualName || 'Nom à renseigner',
        subtitle: manualName ? null : null,
      }
    })

    const min = requirement.minCount ?? (requirement.required ? 1 : 0)
    const max = requirement.maxCount ?? null
    const completed = normalizedEntries.filter((entry) => entry.status === 'complete').length
    const issues = []

    if (completed < min) {
      issues.push({ message: `Minimum ${min} sélection(s) requise(s)`, kind: 'error', anchor: `piece-group-${requirement.id}` })
    }

    if (max !== null && completed > max) {
      issues.push({ message: `Maximum ${max} dépassé`, kind: 'error', anchor: `piece-group-${requirement.id}` })
    }

    if (!requirement.allowNewModels && normalizedEntries.some((entry) => entry.mode === 'manual' && entry.status === 'complete')) {
      issues.push({ message: "Ce groupe n'autorise que les modèles existants.", kind: 'error', anchor: `piece-group-${requirement.id}` })
    }

    if (normalizedEntries.some((entry) => entry.status !== 'complete')) {
      issues.push({ message: 'Compléter les sélections restantes.', kind: 'warning', anchor: `piece-group-${requirement.id}` })
    }

    const status = issues.some((issue) => issue.kind === 'error')
      ? 'error'
      : issues.length > 0
        ? 'warning'
        : 'ready'

    return {
      id: requirement.id,
      label: requirement.label || requirement.typePiece?.name || 'Groupe de pièces',
      typeName: requirement.typePiece?.name || 'Non défini',
      min,
      max,
      entries: normalizedEntries,
      issues,
      completed,
      total: normalizedEntries.length,
      status,
    }
  })

  const aggregatedIssues = [
    ...baseIssues.map((issue) => ({ ...issue, scope: 'Informations générales' })),
    ...componentGroups.flatMap((group) => group.issues.map((issue) => ({ ...issue, scope: group.label }))),
    ...pieceGroups.flatMap((group) => group.issues.map((issue) => ({ ...issue, scope: group.label }))),
  ]

  const statuses = [
    baseStatus,
    ...componentGroups.map((group) => group.status),
    ...pieceGroups.map((group) => group.status),
  ]

  const overallStatus = statuses.includes('error')
    ? 'error'
    : statuses.includes('warning')
      ? 'warning'
      : 'ready'

  return {
    base: {
      fields: baseFields,
      issues: baseIssues,
      status: baseStatus,
    },
    componentGroups,
    pieceGroups,
    type: {
      name: type.name,
      category: type.category || null,
      hasStructuredDefinition:
        (type.componentRequirements?.length || 0) > 0 || (type.pieceRequirements?.length || 0) > 0,
    },
    status: overallStatus,
    ready: overallStatus === 'ready',
    issues: aggregatedIssues,
  }
})

const blockingPreviewIssues = computed(() => {
  if (!machinePreview.value) {
    return []
  }
  return machinePreview.value.issues.filter((issue) => issue.kind === 'error')
})

const canCreateMachine = computed(() => {
  if (!machinePreview.value) {
    return false
  }
  return blockingPreviewIssues.value.length === 0
})

const highlightClasses = ['ring', 'ring-primary', 'ring-offset-2']

const scrollToAnchor = (anchor) => {
  if (!anchor || typeof window === 'undefined' || typeof document === 'undefined') {
    return
  }
  const target = document.getElementById(anchor)
  if (!target) {
    return
  }
  target.scrollIntoView({ behavior: 'smooth', block: 'center' })
  highlightClasses.forEach((cls) => target.classList.add(cls))
  window.setTimeout(() => {
    highlightClasses.forEach((cls) => target.classList.remove(cls))
  }, 1500)
}

const handleIssueClick = (issue) => {
  if (!issue?.anchor) {
    return
  }
  scrollToAnchor(issue.anchor)
}

// Methods
const finalizeMachineCreation = async () => {
  if (!selectedMachineType.value) {
    toast.showError('Merci de sélectionner un type de machine')
    return
  }

  const type = selectedMachineType.value

  const baseMachineData = {
    name: newMachine.name,
    siteId: newMachine.siteId,
    reference: newMachine.reference,
    emplacement: newMachine.emplacement,
    typeMachineId: type.id,
  }

  const hasRequirements = (type.componentRequirements?.length || 0) > 0 || (type.pieceRequirements?.length || 0) > 0

  let componentSelections = []
  let pieceSelections = []

  if (hasRequirements) {
    const validationResult = validateRequirementSelections(type)
    if (!validationResult.valid) {
      toast.showError(validationResult.error)
      return
    }
    componentSelections = validationResult.componentSelections
    pieceSelections = validationResult.pieceSelections
  }

  const payload = {
    ...baseMachineData,
    ...(hasRequirements
      ? {
          componentSelections,
          pieceSelections,
        }
      : {}),
  }

  const result = hasRequirements
    ? await createMachine(payload)
    : await createMachineFromType(baseMachineData, type)
  
  if (result.success) {
    // Reset form
    newMachine.name = ''
    newMachine.siteId = ''
    newMachine.typeMachineId = ''
    newMachine.reference = ''
    newMachine.emplacement = ''
    clearRequirementSelections()
    showAddMachineModal.value = false
    }
}

const viewMachineDetails = (machine) => {
  // Naviguer vers la page de détails de la machine en mode lecture seule
  navigateTo(`/machine/${machine.id}`)
}

const editMachine = (machine) => {
  // Naviguer vers la page machine en mode édition
  navigateTo(`/machine/${machine.id}?edit=true`)
}

const confirmDeleteMachine = async (machine) => {
  const { showError, showSuccess } = toast

  if (confirm(`Êtes-vous sûr de vouloir supprimer la machine "${machine.name}" ? Cette action est irréversible.`)) {
    try {
      const result = await deleteMachine(machine.id)
      if (result.success) {
        showSuccess(`Machine "${machine.name}" supprimée avec succès`)
      } else {
        showError(`Erreur lors de la suppression: ${result.error}`)
      }
    } catch (error) {
      showError(`Erreur lors de la suppression: ${error.message}`)
    }
  }
}

const closeCreateMachineModal = () => {
  showAddMachineModal.value = false
  newMachine.name = ''
  newMachine.siteId = ''
  newMachine.typeMachineId = ''
  newMachine.reference = ''
  newMachine.emplacement = ''
  clearRequirementSelections()
  closeCreateComponentModelModal()
  closeCreatePieceModelModal()
}

// Lifecycle
onMounted(async () => {
  await Promise.all([
    loadMachines(),
    loadSites(),
    loadMachineTypes()
  ])
})

watch(
  () => route.query.add,
  async (shouldOpen) => {
    if (shouldOpen === 'true') {
      showAddMachineModal.value = true
      await navigateTo('/machines', { replace: true })
    }
  },
  { immediate: true }
)

watch(
  () => newMachine.typeMachineId,
  async (typeId) => {
    clearRequirementSelections()
    if (!typeId) {
      return
    }

    const type = machineTypes.value.find((item) => item.id === typeId)
    if (!type) {
      return
    }

    await initializeRequirementSelections(type)
  }
)

const clearRequirementSelections = () => {
  Object.keys(componentRequirementSelections).forEach((key) => {
    delete componentRequirementSelections[key]
  })
  Object.keys(pieceRequirementSelections).forEach((key) => {
    delete pieceRequirementSelections[key]
  })
}

const initializeRequirementSelections = async (type) => {
  const componentRequirements = type.componentRequirements || []
  const pieceRequirements = type.pieceRequirements || []

  const componentTypeIds = new Set()
  const pieceTypeIds = new Set()

  componentRequirements.forEach((requirement) => {
    componentTypeIds.add(requirement.typeComposantId)
    const min = requirement.minCount ?? (requirement.required ? 1 : 0)
    const initialCount = Math.max(min, requirement.required ? 1 : 0)
    const entries = []
    for (let index = 0; index < initialCount; index += 1) {
      entries.push(createComponentSelectionEntry())
    }
    componentRequirementSelections[requirement.id] = entries
  })

  pieceRequirements.forEach((requirement) => {
    pieceTypeIds.add(requirement.typePieceId)
    const min = requirement.minCount ?? (requirement.required ? 1 : 0)
    const initialCount = Math.max(min, requirement.required ? 1 : 0)
    const entries = []
    for (let index = 0; index < initialCount; index += 1) {
      entries.push(createPieceSelectionEntry())
    }
    pieceRequirementSelections[requirement.id] = entries
  })

  await Promise.all([
    ...Array.from(componentTypeIds).map((id) => loadComponentModels(id)),
    ...Array.from(pieceTypeIds).map((id) => loadPieceModels(id)),
  ])
}

const createComponentSelectionEntry = () => ({
  mode: 'model',
  componentModelId: '',
  name: '',
})

const createPieceSelectionEntry = () => ({
  mode: 'model',
  pieceModelId: '',
  name: '',
})

const getComponentRequirementEntries = (requirementId) => componentRequirementSelections[requirementId] || []

const getPieceRequirementEntries = (requirementId) => pieceRequirementSelections[requirementId] || []

const addComponentSelectionEntry = (requirement) => {
  const entries = getComponentRequirementEntries(requirement.id)
  const max = requirement.maxCount ?? null
  if (max !== null && entries.length >= max) {
    toast.showError(`Vous ne pouvez pas ajouter plus de ${max} composant(s) pour ${requirement.label || requirement.typeComposant?.name || 'ce groupe'}`)
    return
  }
  componentRequirementSelections[requirement.id] = [...entries, createComponentSelectionEntry()]
}

const removeComponentSelectionEntry = (requirementId, index) => {
  const entries = getComponentRequirementEntries(requirementId)
  componentRequirementSelections[requirementId] = entries.filter((_, i) => i !== index)
}

const setComponentSelectionMode = (requirementId, index, mode) => {
  const entries = getComponentRequirementEntries(requirementId)
  componentRequirementSelections[requirementId] = entries.map((entry, i) => {
    if (i !== index) return entry
    if (mode === 'model') {
      return { ...entry, mode: 'model', componentModelId: entry.componentModelId || '', name: '' }
    }
    return { ...entry, mode: 'manual', componentModelId: '', name: entry.name || '' }
  })
}

const updateComponentSelectionEntry = (requirementId, index, patch) => {
  const entries = getComponentRequirementEntries(requirementId)
  componentRequirementSelections[requirementId] = entries.map((entry, i) =>
    i === index ? { ...entry, ...patch } : entry
  )
}

const addPieceSelectionEntry = (requirement) => {
  const entries = getPieceRequirementEntries(requirement.id)
  const max = requirement.maxCount ?? null
  if (max !== null && entries.length >= max) {
    toast.showError(`Vous ne pouvez pas ajouter plus de ${max} pièce(s) pour ${requirement.label || requirement.typePiece?.name || 'ce groupe'}`)
    return
  }
  pieceRequirementSelections[requirement.id] = [...entries, createPieceSelectionEntry()]
}

const removePieceSelectionEntry = (requirementId, index) => {
  const entries = getPieceRequirementEntries(requirementId)
  pieceRequirementSelections[requirementId] = entries.filter((_, i) => i !== index)
}

const setPieceSelectionMode = (requirementId, index, mode) => {
  const entries = getPieceRequirementEntries(requirementId)
  pieceRequirementSelections[requirementId] = entries.map((entry, i) => {
    if (i !== index) return entry
    if (mode === 'model') {
      return { ...entry, mode: 'model', pieceModelId: entry.pieceModelId || '', name: '' }
    }
    return { ...entry, mode: 'manual', pieceModelId: '', name: entry.name || '' }
  })
}

const updatePieceSelectionEntry = (requirementId, index, patch) => {
  const entries = getPieceRequirementEntries(requirementId)
  pieceRequirementSelections[requirementId] = entries.map((entry, i) =>
    i === index ? { ...entry, ...patch } : entry
  )
}

const validateRequirementSelections = (type) => {
  const errors = []
  const componentSelectionsPayload = []
  const pieceSelectionsPayload = []

  for (const requirement of type.componentRequirements || []) {
    const entries = getComponentRequirementEntries(requirement.id)
    const usableEntries = entries.filter((entry) => {
      if (entry.mode === 'model') {
        return !!entry.componentModelId
      }
      return !!entry.name && entry.name.trim().length > 0
    })

    const min = requirement.minCount ?? (requirement.required ? 1 : 0)
    const max = requirement.maxCount ?? null

    if (usableEntries.length < min) {
      errors.push(`Le groupe "${requirement.label || requirement.typeComposant?.name || 'Composants'}" nécessite au moins ${min} élément(s).`)
    }

    if (max !== null && usableEntries.length > max) {
      errors.push(`Le groupe "${requirement.label || requirement.typeComposant?.name || 'Composants'}" ne peut dépasser ${max} élément(s).`)
    }

    if (!requirement.allowNewModels && usableEntries.some((entry) => entry.mode === 'manual')) {
      errors.push(`Le groupe "${requirement.label || requirement.typeComposant?.name || 'Composants'}" n'autorise que les modèles existants.`)
    }

    usableEntries.forEach((entry) => {
      if (entry.mode === 'model') {
        componentSelectionsPayload.push({
          requirementId: requirement.id,
          componentModelId: entry.componentModelId,
        })
      } else {
        componentSelectionsPayload.push({
          requirementId: requirement.id,
          definition: {
            name: entry.name.trim(),
          },
        })
      }
    })
  }

  for (const requirement of type.pieceRequirements || []) {
    const entries = getPieceRequirementEntries(requirement.id)
    const usableEntries = entries.filter((entry) => {
      if (entry.mode === 'model') {
        return !!entry.pieceModelId
      }
      return !!entry.name && entry.name.trim().length > 0
    })

    const min = requirement.minCount ?? (requirement.required ? 1 : 0)
    const max = requirement.maxCount ?? null

    if (usableEntries.length < min) {
      errors.push(`Le groupe "${requirement.label || requirement.typePiece?.name || 'Pièces'}" nécessite au moins ${min} élément(s).`)
    }

    if (max !== null && usableEntries.length > max) {
      errors.push(`Le groupe "${requirement.label || requirement.typePiece?.name || 'Pièces'}" ne peut dépasser ${max} élément(s).`)
    }

    if (!requirement.allowNewModels && usableEntries.some((entry) => entry.mode === 'manual')) {
      errors.push(`Le groupe "${requirement.label || requirement.typePiece?.name || 'Pièces'}" n'autorise que les modèles existants.`)
    }

    usableEntries.forEach((entry) => {
      if (entry.mode === 'model') {
        pieceSelectionsPayload.push({
          requirementId: requirement.id,
          pieceModelId: entry.pieceModelId,
        })
      } else {
        pieceSelectionsPayload.push({
          requirementId: requirement.id,
          definition: {
            name: entry.name.trim(),
          },
        })
      }
    })
  }

  if (errors.length > 0) {
    return { valid: false, error: errors[0] }
  }

  return {
    valid: true,
    componentSelections: componentSelectionsPayload,
    pieceSelections: pieceSelectionsPayload,
  }
}

const openCreateComponentModelModal = (requirement) => {
  createComponentModelModal.open = true
  createComponentModelModal.requirement = requirement
  createComponentModelModal.requirementId = requirement.id
  createComponentModelModal.entryIndex = null
  createComponentModelModal.name = ''
  createComponentModelModal.description = ''
}

const closeCreateComponentModelModal = () => {
  createComponentModelModal.open = false
  createComponentModelModal.requirement = null
  createComponentModelModal.requirementId = null
  createComponentModelModal.entryIndex = null
  createComponentModelModal.name = ''
  createComponentModelModal.description = ''
  createComponentModelModal.submitting = false
}

const submitCreateComponentModel = async () => {
  if (!createComponentModelModal.requirement || !createComponentModelModal.name.trim()) {
    return
  }
  createComponentModelModal.submitting = true
  try {
    const payload = {
      name: createComponentModelModal.name.trim(),
      description: createComponentModelModal.description.trim() || undefined,
      typeComposantId: createComponentModelModal.requirement.typeComposantId,
      structure: {},
    }
    const result = await createComponentModel(payload)
    if (result.success) {
      await loadComponentModels(createComponentModelModal.requirement.typeComposantId)
      const entries = getComponentRequirementEntries(createComponentModelModal.requirement.id)
      const targetIndex = entries.findIndex((entry) => entry.mode === 'model' && !entry.componentModelId)
      if (targetIndex !== -1) {
        updateComponentSelectionEntry(createComponentModelModal.requirement.id, targetIndex, {
          mode: 'model',
          componentModelId: result.data.id,
        })
      } else {
        addComponentSelectionEntry(createComponentModelModal.requirement)
        updateComponentSelectionEntry(
          createComponentModelModal.requirement.id,
          getComponentRequirementEntries(createComponentModelModal.requirement.id).length - 1,
          {
            mode: 'model',
            componentModelId: result.data.id,
          },
        )
      }
      toast.showSuccess(`Modèle "${result.data.name}" créé`)
      closeCreateComponentModelModal()
    }
  } catch (error) {
    toast.showError('Impossible de créer le modèle de composant')
  } finally {
    createComponentModelModal.submitting = false
  }
}

const openCreatePieceModelModal = (requirement) => {
  createPieceModelModal.open = true
  createPieceModelModal.requirement = requirement
  createPieceModelModal.requirementId = requirement.id
  createPieceModelModal.entryIndex = null
  createPieceModelModal.name = ''
  createPieceModelModal.description = ''
}

const closeCreatePieceModelModal = () => {
  createPieceModelModal.open = false
  createPieceModelModal.requirement = null
  createPieceModelModal.requirementId = null
  createPieceModelModal.entryIndex = null
  createPieceModelModal.name = ''
  createPieceModelModal.description = ''
  createPieceModelModal.submitting = false
}

const submitCreatePieceModel = async () => {
  if (!createPieceModelModal.requirement || !createPieceModelModal.name.trim()) {
    return
  }
  createPieceModelModal.submitting = true
  try {
    const payload = {
      name: createPieceModelModal.name.trim(),
      description: createPieceModelModal.description.trim() || undefined,
      typePieceId: createPieceModelModal.requirement.typePieceId,
      structure: {},
    }
    const result = await createPieceModel(payload)
    if (result.success) {
      await loadPieceModels(createPieceModelModal.requirement.typePieceId)
      const entries = getPieceRequirementEntries(createPieceModelModal.requirement.id)
      const targetIndex = entries.findIndex((entry) => entry.mode === 'model' && !entry.pieceModelId)
      if (targetIndex !== -1) {
        updatePieceSelectionEntry(createPieceModelModal.requirement.id, targetIndex, {
          mode: 'model',
          pieceModelId: result.data.id,
        })
      } else {
        addPieceSelectionEntry(createPieceModelModal.requirement)
        updatePieceSelectionEntry(
          createPieceModelModal.requirement.id,
          getPieceRequirementEntries(createPieceModelModal.requirement.id).length - 1,
          {
            mode: 'model',
            pieceModelId: result.data.id,
          },
        )
      }
      toast.showSuccess(`Modèle "${result.data.name}" créé`)
      closeCreatePieceModelModal()
    }
  } catch (error) {
    toast.showError('Impossible de créer le modèle de pièce')
  } finally {
    createPieceModelModal.submitting = false
  }
}
</script> 
