<template>
  <main class="container mx-auto px-6 py-8">
    <div class="max-w-5xl mx-auto">
      <div class="flex flex-wrap items-center justify-between gap-3 mb-6">
        <div>
          <h1 class="text-2xl font-bold">
            Nouvelle machine
          </h1>
          <p class="text-sm text-gray-500">
            Renseignez les informations et la configuration avant de créer la machine.
          </p>
        </div>
        <NuxtLink to="/machines" class="btn btn-ghost">
          Annuler
        </NuxtLink>
      </div>

      <form class="space-y-6" @submit.prevent="finalizeMachineCreation">
        <div class="card bg-base-100 shadow-lg">
          <div class="card-body space-y-6">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div class="form-control">
                <label class="label" for="machine-field-name">
                  <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" for="machine-field-site">
                  <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>

            <div class="grid grid-cols-1 md:grid-cols-2 gap-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 v-if="selectedMachineType" class="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="space-y-4">
              <h4 class="text-sm font-semibold">
                Sélection des composants
              </h4>

              <div
                v-for="requirement in selectedMachineType.componentRequirements"
                :id="`component-group-${requirement.id}`"
                :key="requirement.id"
                class="border border-base-200 rounded-lg p-4 space-y-3"
              >
                <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"
                      :disabled="requirement.maxCount !== null && getComponentRequirementEntries(requirement.id).length >= requirement.maxCount"
                      @click="addComponentSelectionEntry(requirement)"
                    >
                      <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'"
                        :disabled="!requirement.allowNewModels"
                        @change="setComponentSelectionMode(requirement.id, entryIndex, 'manual')"
                      >
                      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="space-y-4">
              <h4 class="text-sm font-semibold">
                Sélection des pièces principales
              </h4>

              <div
                v-for="requirement in selectedMachineType.pieceRequirements"
                :id="`piece-group-${requirement.id}`"
                :key="requirement.id"
                class="border border-base-200 rounded-lg p-4 space-y-3"
              >
                <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"
                      :disabled="requirement.maxCount !== null && getPieceRequirementEntries(requirement.id).length >= requirement.maxCount"
                      @click="addPieceSelectionEntry(requirement)"
                    >
                      <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="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 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="space-y-4">
              <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>
                        </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"
            >
              Compléter les informations bloquantes avant de créer la machine.
            </div>

            <div class="flex justify-end gap-3 pt-4 border-t border-base-200">
              <NuxtLink to="/machines" class="btn btn-outline">
                Annuler
              </NuxtLink>
              <button
                type="submit"
                class="btn btn-primary"
                :disabled="!canCreateMachine || submitting"
                :class="{ loading: submitting }"
              >
                Créer la machine
              </button>
            </div>
          </div>
        </div>
      </form>
    </div>

    <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"
            />
          </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>

    <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"
            />
          </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>
  </main>
</template>

<script setup>
import { ref, reactive, computed, watch, onMounted } 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 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 { createMachine, createMachineFromType } = useMachines()
const { sites, loadSites } = useSites()
const { machineTypes, loadMachineTypes } = useMachineTypesApi()
const { loadComponentModels, getComponentModelsForType, loadingComponentModels, createComponentModel } = useComponentModels()
const { loadPieceModels, getPieceModelsForType, loadingPieceModels, createPieceModel } = usePieceModels()
const toast = useToast()

const submitting = ref(false)

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

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 selectedMachineType = computed(() => {
  if (!newMachine.typeMachineId) {
    return null
  }
  return machineTypes.value.find(type => type.id === newMachine.typeMachineId) || null
})

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

const getComponentRequirementEntries = requirementId => componentRequirementSelections[requirementId] || []
const getPieceRequirementEntries = requirementId => pieceRequirementSelections[requirementId] || []

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 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'
    }
  ]

  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) => {
      const model = resolvePieceModel(requirement, entry.pieceModelId)
      return {
        key: `${requirement.id}-${index}`,
        status: model ? 'complete' : 'pending',
        title: model ? model.name : 'Sélectionner un modèle',
        subtitle: model?.description || 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 (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)
}

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

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

const createPieceSelectionEntry = () => ({
  pieceModelId: ''
})

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 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 => !!entry.pieceModelId)

    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).`)
    }

    usableEntries.forEach((entry) => {
      pieceSelectionsPayload.push({
        requirementId: requirement.id,
        pieceModelId: entry.pieceModelId
      })
    })
  }

  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.pieceModelId)
      if (targetIndex !== -1) {
        updatePieceSelectionEntry(createPieceModelModal.requirement.id, targetIndex, {
          pieceModelId: result.data.id
        })
      } else {
        addPieceSelectionEntry(createPieceModelModal.requirement)
        updatePieceSelectionEntry(
          createPieceModelModal.requirement.id,
          getPieceRequirementEntries(createPieceModelModal.requirement.id).length - 1,
          {
            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
  }
}

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 finalizeMachineCreation = async () => {
  if (submitting.value) {
    return
  }
  if (!selectedMachineType.value) {
    toast.showError('Merci de sélectionner un type de machine')
    return
  }
  if (!canCreateMachine.value) {
    toast.showError('Compléter les informations obligatoires avant de créer la machine')
    return
  }

  submitting.value = true
  try {
    const type = selectedMachineType.value
    const baseMachineData = {
      name: newMachine.name,
      siteId: newMachine.siteId,
      reference: newMachine.reference,
      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) {
      newMachine.name = ''
      newMachine.siteId = ''
      newMachine.typeMachineId = ''
      newMachine.reference = ''
      clearRequirementSelections()
      await navigateTo('/machines')
    } else if (result.error) {
      toast.showError(`Impossible de créer la machine: ${result.error}`)
    }
  } catch (error) {
    toast.showError(`Erreur lors de la création: ${error.message}`)
  } finally {
    submitting.value = false
  }
}

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

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

    await initializeRequirementSelections(type)
  }
)

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