<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="c.finalizeMachineCreation">
        <div class="card bg-base-100 shadow-lg">
          <div class="card-body space-y-6">
            <!-- Basic fields -->
            <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="c.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="c.newMachine.siteId" class="select select-bordered" required>
                  <option value="">
                    Sélectionner un site
                  </option>
                  <option v-for="site in c.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>
                <SearchSelect
                  v-model="c.newMachine.typeMachineId"
                  :options="c.machineTypes"
                  :loading="c.machineTypesLoading"
                  placeholder="Rechercher un type…"
                  empty-text="Aucun type trouvé"
                  :option-label="c.machineTypeLabel"
                  :option-description="c.machineTypeDescription"
                />
              </div>

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

            <!-- Type structure summary -->
            <div v-if="c.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">{{ c.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">{{ c.selectedMachineType.pieceRequirements?.length || 0 }}</span>
                </span>
                <span class="inline-flex items-center gap-2">
                  <span class="font-medium">Produits requis :</span>
                  <span class="badge badge-sm">{{ c.selectedMachineType.productRequirements?.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">{{ c.selectedMachineType.category || 'N/A' }}</span>
                </span>
              </div>
              <p
                v-if="(c.selectedMachineType.componentRequirements?.length || 0) === 0 && (c.selectedMachineType.pieceRequirements?.length || 0) === 0 && (c.selectedMachineType.productRequirements?.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>

            <!-- Requirement selectors -->
            <RequirementComponentSelector
              :requirements="c.selectedMachineType?.componentRequirements || []"
              :loading="c.composantsLoading"
              :get-entries="c.getComponentRequirementEntries"
              :get-options="c.getComponentOptions"
              :resolve-type-label="c.resolveComponentRequirementTypeLabel"
              :find-by-id="c.findComponentById"
              :option-label="c.componentOptionLabel"
              :option-description="c.componentOptionDescription"
              @add-entry="c.addComponentSelectionEntry"
              @remove-entry="c.removeComponentSelectionEntry"
              @set-component="c.setComponentRequirementComponent"
            />

            <RequirementPieceSelector
              :requirements="c.selectedMachineType?.pieceRequirements || []"
              :loading="c.piecesLoading"
              :piece-loading-by-key="c.pieceLoadingByKey"
              :get-entries="c.getPieceRequirementEntries"
              :get-options="c.getPieceOptions"
              :get-piece-key="c.getPieceKey"
              :resolve-type-label="c.resolvePieceRequirementTypeLabel"
              :find-by-id="c.findPieceById"
              :option-label="c.pieceOptionLabel"
              :option-description="c.pieceOptionDescription"
              @add-entry="c.addPieceSelectionEntry"
              @remove-entry="c.removePieceSelectionEntry"
              @set-piece="c.setPieceRequirementPiece"
              @search="c.fetchPieceOptions"
            />

            <RequirementProductSelector
              :requirements="c.selectedMachineType?.productRequirements || []"
              :products-loading="c.productsLoading"
              :get-entries="c.getProductRequirementEntries"
              :get-product-options="c.getProductOptions"
              :find-by-id="c.findProductById"
              @add-entry="c.addProductSelectionEntry"
              @remove-entry="c.removeProductSelectionEntry"
              @set-product="c.setProductRequirementProduct"
            />

            <!-- Preview -->
            <MachineCreatePreview :preview="c.machinePreview" />

            <!-- Blocking issues warning -->
            <div
              v-if="c.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>

            <!-- Actions -->
            <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="!c.canCreateMachine || c.submitting"
                :class="{ loading: c.submitting }"
              >
                Créer la machine
              </button>
            </div>
          </div>
        </div>
      </form>
    </div>
  </main>
</template>

<script setup>
import { proxyRefs } from 'vue'
import { useMachineCreatePage } from '~/composables/useMachineCreatePage'
import SearchSelect from '~/components/common/SearchSelect.vue'
import RequirementComponentSelector from '~/components/machine/create/RequirementComponentSelector.vue'
import RequirementPieceSelector from '~/components/machine/create/RequirementPieceSelector.vue'
import RequirementProductSelector from '~/components/machine/create/RequirementProductSelector.vue'
import MachineCreatePreview from '~/components/machine/create/MachineCreatePreview.vue'

const c = proxyRefs(useMachineCreatePage())
</script>
