<template>
  <main class="mx-auto flex w-full max-w-5xl flex-col gap-8 px-4 py-8 sm:px-6 lg:px-8">
    <header class="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
      <div class="space-y-1">
        <h1 class="text-3xl font-semibold text-base-content">Nouvelle pièce</h1>
        <p class="text-sm text-base-content/70">
          Choisissez la catégorie adaptée puis renseignez toutes les informations de votre pièce.
        </p>
      </div>
      <NuxtLink to="/pieces-catalog" class="btn btn-ghost btn-sm md:btn-md self-start">
        Retour au catalogue
      </NuxtLink>
    </header>

    <section class="card border border-base-200 bg-base-100 shadow-sm">
      <div class="card-body space-y-6">
        <div class="grid grid-cols-1 gap-4 md:grid-cols-2">
          <div class="form-control">
            <label class="label">
              <span class="label-text">Catégorie de pièce</span>
            </label>
            <select
              v-model="selectedTypeId"
              class="select select-bordered select-sm md:select-md"
              :disabled="loadingTypes || submitting"
              required
            >
              <option value="">Sélectionner une catégorie</option>
              <option
                v-for="type in pieceTypeList"
                :key="type.id"
                :value="type.id"
              >
                {{ type.name }}
              </option>
            </select>
            <p v-if="loadingTypes" class="text-xs text-gray-500 mt-1">
              Chargement des catégories…
            </p>
          </div>
        </div>

        <div class="grid grid-cols-1 gap-4 md:grid-cols-2">
          <div class="form-control">
            <label class="label">
              <span class="label-text">Nom de la pièce</span>
            </label>
            <input
              v-model="creationForm.name"
              type="text"
              class="input input-bordered input-sm md:input-md"
              :disabled="submitting || !selectedType"
              placeholder="Nom affiché dans le catalogue"
              required
            >
          </div>
        </div>

        <div class="grid grid-cols-1 gap-4 md:grid-cols-2">
          <div class="form-control">
            <label class="label">
              <span class="label-text">Référence</span>
            </label>
            <input
              v-model="creationForm.reference"
              type="text"
              class="input input-bordered input-sm md:input-md"
              :disabled="submitting || !selectedType"
              placeholder="Référence interne ou constructeur"
            >
          </div>

          <div class="form-control">
            <label class="label">
              <span class="label-text">Constructeur</span>
            </label>
            <ConstructeurSelect
              v-model="creationForm.constructeurId"
              class="w-full"
              :disabled="submitting || !selectedType"
              placeholder="Rechercher un constructeur..."
            />
          </div>
        </div>

        <div class="grid grid-cols-1 gap-4 md:grid-cols-2">
          <div class="form-control">
            <label class="label">
              <span class="label-text">Prix indicatif (€)</span>
            </label>
            <input
              v-model="creationForm.prix"
              type="number"
              step="0.01"
              min="0"
              class="input input-bordered input-sm md:input-md"
              :disabled="submitting || !selectedType"
              placeholder="Valeur indicatrice"
            >
          </div>
        </div>

        <div v-if="selectedType" class="space-y-3 rounded-lg border border-base-200 bg-base-200/40 p-4">
          <div class="flex items-center justify-between gap-4">
            <div>
              <h2 class="font-semibold text-base-content">Squelette sélectionné</h2>
              <p class="text-xs text-base-content/70">
                {{ selectedType.description || 'Ce squelette définit la structure et les champs personnalisés de la pièce.' }}
              </p>
            </div>
            <span class="badge badge-outline">{{ formatPieceStructurePreview(selectedType.structure) }}</span>
          </div>

          <details v-if="selectedType.structure" class="collapse collapse-arrow bg-base-100">
            <summary class="collapse-title text-sm font-medium">
              Consulter le détail du squelette
            </summary>
            <div class="collapse-content space-y-2 text-sm text-base-content/80">
              <div v-if="getStructureCustomFields(selectedType.structure).length" class="space-y-1">
                <h3 class="font-semibold text-sm text-base-content">Champs personnalisés</h3>
                <ul class="list-disc list-inside space-y-1">
                  <li v-for="field in getStructureCustomFields(selectedType.structure)" :key="field.name">
                    <span class="font-medium">{{ field.name }}</span>
                    <span v-if="field.value !== undefined && field.value !== null"> : {{ field.value }}</span>
                  </li>
                </ul>
              </div>

              <p v-else class="text-xs text-base-content/70">
                Ce squelette ne définit pas encore de champs personnalisés.
              </p>
            </div>
          </details>
        </div>

        <div v-if="customFieldInputs.length" class="space-y-4 rounded-lg border border-base-200 bg-base-200/40 p-4">
          <header class="space-y-1">
            <h2 class="font-semibold text-base-content">Champs personnalisés</h2>
            <p class="text-xs text-base-content/70">
              Renseignez les valeurs propres à cette pièce. Ces champs complètent le squelette sélectionné.
            </p>
          </header>
          <div class="grid grid-cols-1 gap-4 md:grid-cols-2">
            <div
              v-for="(field, index) in customFieldInputs"
              :key="fieldKey(field, index)"
              class="form-control"
            >
              <label class="label">
                <span class="label-text">{{ field.name }}</span>
                <span v-if="field.required" class="label-text-alt text-error">*</span>
              </label>
              <input
                v-if="field.type === 'text'"
                v-model="field.value"
                type="text"
                class="input input-bordered input-sm md:input-md"
                :required="field.required"
                :disabled="submitting"
              >
              <input
                v-else-if="field.type === 'number'"
                v-model="field.value"
                type="number"
                step="0.01"
                class="input input-bordered input-sm md:input-md"
                :required="field.required"
                :disabled="submitting"
              >
              <select
                v-else-if="field.type === 'select'"
                v-model="field.value"
                class="select select-bordered select-sm md:select-md"
                :required="field.required"
                :disabled="submitting"
              >
                <option value="">Sélectionner...</option>
                <option
                  v-for="option in field.options"
                  :key="option"
                  :value="option"
                >
                  {{ option }}
                </option>
              </select>
              <div v-else-if="field.type === 'boolean'" class="flex items-center gap-2">
                <input
                  v-model="field.value"
                  type="checkbox"
                  class="checkbox checkbox-sm"
                  true-value="true"
                  false-value="false"
                  :disabled="submitting"
                >
                <span class="text-sm">{{ field.value === 'true' ? 'Oui' : 'Non' }}</span>
              </div>
              <input
                v-else-if="field.type === 'date'"
                v-model="field.value"
                type="date"
                class="input input-bordered input-sm md:input-md"
                :required="field.required"
                :disabled="submitting"
              >
              <input
                v-else
                v-model="field.value"
                type="text"
                class="input input-bordered input-sm md:input-md"
                :required="field.required"
                :disabled="submitting"
              >
            </div>
          </div>
        </div>

        <div class="flex flex-col gap-3 md:flex-row md:justify-end">
          <NuxtLink to="/pieces-catalog" class="btn btn-ghost" :class="{ 'btn-disabled': submitting }">
            Annuler
          </NuxtLink>
          <button type="button" class="btn btn-primary" :disabled="!canSubmit" @click="submitCreation">
            <span v-if="submitting" class="loading loading-spinner loading-sm mr-2"></span>
            Créer la pièce
          </button>
        </div>
      </div>
    </section>
  </main>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { useRoute, useRouter } from '#imports'
import ConstructeurSelect from '~/components/ConstructeurSelect.vue'
import { usePieceTypes } from '~/composables/usePieceTypes'
import { usePieces } from '~/composables/usePieces'
import { useToast } from '~/composables/useToast'
import { useCustomFields } from '~/composables/useCustomFields'
import { formatPieceStructurePreview } from '~/shared/modelUtils'
import type { PieceModelStructure } from '~/shared/types/inventory'
import type { ModelType } from '~/services/modelTypes'

interface PieceCatalogType extends ModelType {
  structure: PieceModelStructure | null
  customFields?: Array<Record<string, any>>
}

const route = useRoute()
const router = useRouter()

const { pieceTypes, loadPieceTypes, loadingPieceTypes } = usePieceTypes()
const { createPiece } = usePieces()
const toast = useToast()
const { upsertCustomFieldValue, updateCustomFieldValue } = useCustomFields()

const initialTypeId = ref<string>(typeof route.query.typeId === 'string' ? route.query.typeId : '')
const selectedTypeId = ref<string>(initialTypeId.value)
const submitting = ref(false)
const creationForm = reactive({
  name: '' as string,
  reference: '' as string,
  constructeurId: null as string | null,
  prix: '' as string,
})

const lastSuggestedName = ref('')
const customFieldInputs = ref<CustomFieldInput[]>([])

watch(
  () => route.query.typeId,
  (value) => {
    if (typeof value === 'string') {
      selectedTypeId.value = value
    }
  },
)

watch(selectedTypeId, (id) => {
  const current = typeof route.query.typeId === 'string' ? route.query.typeId : ''
  if ((id || '') === current) {
    return
  }
  const nextQuery = { ...route.query }
  if (id) {
    nextQuery.typeId = id
  } else {
    delete nextQuery.typeId
  }
  router.replace({ path: route.path, query: nextQuery }).catch(() => {})
})

const loadingTypes = computed(() => loadingPieceTypes.value)
const pieceTypeList = computed<PieceCatalogType[]>(() => (pieceTypes.value || []) as PieceCatalogType[])

const selectedType = computed(() => {
  if (!selectedTypeId.value) {
    return null
  }
  return pieceTypeList.value.find((type) => type.id === selectedTypeId.value) ?? null
})

watch(selectedType, (type) => {
  if (!type) {
    clearCreationForm()
    customFieldInputs.value = []
    return
  }
  if (!creationForm.name || creationForm.name === lastSuggestedName.value) {
    creationForm.name = type.name
  }
  lastSuggestedName.value = creationForm.name
  customFieldInputs.value = normalizeCustomFieldInputs(type.structure)
})

const requiredCustomFieldsFilled = computed(() =>
  customFieldInputs.value.every((field) => {
    if (!field.required) {
      return true
    }
    if (field.type === 'boolean') {
      return field.value === 'true' || field.value === 'false'
    }
    return toFieldString(field.value).trim() !== ''
  }),
)

const canSubmit = computed(() => Boolean(
  selectedType.value &&
  creationForm.name &&
  requiredCustomFieldsFilled.value &&
  !submitting.value,
))

const toFieldString = (value: unknown): string => {
  if (value === null || value === undefined) {
    return ''
  }
  if (typeof value === 'string') {
    return value
  }
  if (typeof value === 'number' || typeof value === 'boolean') {
    return String(value)
  }
  return ''
}

const getStructureCustomFields = (structure: PieceModelStructure | null) => Array.isArray(structure?.customFields) ? structure.customFields : []

const clearCreationForm = () => {
  creationForm.name = ''
  creationForm.reference = ''
  creationForm.constructeurId = null
  creationForm.prix = ''
  lastSuggestedName.value = ''
}

const submitCreation = async () => {
  if (!selectedType.value) {
    toast.showError('Sélectionnez une catégorie de pièce.')
    return
  }
  const payload: Record<string, any> = {
    name: creationForm.name.trim(),
    typePieceId: selectedType.value.id,
  }

  const reference = creationForm.reference.trim()
  if (reference) {
    payload.reference = reference
  }

  if (creationForm.constructeurId) {
    payload.constructeurId = creationForm.constructeurId
  }

  const rawPrice = typeof creationForm.prix === 'string'
    ? creationForm.prix.trim()
    : creationForm.prix === null || creationForm.prix === undefined
      ? ''
      : String(creationForm.prix).trim()

  if (rawPrice) {
    const parsed = Number(rawPrice)
    if (!Number.isNaN(parsed)) {
      payload.prix = parsed
    }
  }

  submitting.value = true
  try {
    const result = await createPiece(payload)
    if (result.success) {
      await saveCustomFieldValues(result.data)
      toast.showSuccess('Pièce créée avec succès')
      await router.push('/pieces-catalog')
    } else if (result.error) {
      toast.showError(result.error)
    }
  } catch (error: any) {
    toast.showError(error?.message || 'Erreur lors de la création de la pièce')
  } finally {
    submitting.value = false
  }
}

onMounted(async () => {
  await loadPieceTypes()
})

interface CustomFieldInput {
  id: string | null
  name: string
  type: string
  required: boolean
  options: string[]
  value: string
  customFieldId: string | null
  customFieldValueId: string | null
}

const fieldKey = (field: CustomFieldInput, index: number) =>
  field.customFieldValueId || field.id || `${field.name}-${index}`

const normalizeCustomFieldInputs = (structure: PieceModelStructure | null): CustomFieldInput[] => {
  if (!structure || typeof structure !== 'object') {
    return []
  }
  const fields = Array.isArray(structure.customFields) ? structure.customFields : []
  return fields
    .map((field) => normalizeCustomField(field))
    .filter((field): field is CustomFieldInput => field !== null)
}

const normalizeCustomField = (rawField: any): CustomFieldInput | null => {
  if (!rawField || typeof rawField !== 'object') {
    return null
  }
  const name = resolveFieldName(rawField)
  if (!name) {
    return null
  }
  const type = resolveFieldType(rawField)
  const required = !!rawField.required
  const options = Array.isArray(rawField.options)
    ? rawField.options.filter((option: unknown): option is string => typeof option === 'string')
    : []
  const value = formatDefaultValue(type, rawField.value)
  const id = typeof rawField.id === 'string' ? rawField.id : null
  const customFieldId = typeof rawField.customFieldId === 'string' ? rawField.customFieldId : id
  const customFieldValueId = typeof rawField.customFieldValueId === 'string'
    ? rawField.customFieldValueId
    : null

  return { id, name, type, required, options, value, customFieldId, customFieldValueId }
}

const resolveFieldName = (field: any): string => {
  if (typeof field?.name === 'string' && field.name.trim()) {
    return field.name.trim()
  }
  if (typeof field?.key === 'string' && field.key.trim()) {
    return field.key.trim()
  }
  if (typeof field?.label === 'string' && field.label.trim()) {
    return field.label.trim()
  }
  return ''
}

const resolveFieldType = (field: any): string => {
  const allowed = ['text', 'number', 'select', 'boolean', 'date']
  const value = typeof field?.type === 'string' ? field.type.toLowerCase() : ''
  return allowed.includes(value) ? value : 'text'
}

const formatDefaultValue = (type: string, defaultValue: any): string => {
  if (defaultValue === null || defaultValue === undefined) {
    return ''
  }
  if (type === 'boolean') {
    const normalized = String(defaultValue).toLowerCase()
    if (normalized === 'true' || normalized === '1') {
      return 'true'
    }
    if (normalized === 'false' || normalized === '0') {
      return 'false'
    }
    return ''
  }
  return String(defaultValue)
}

const buildCustomFieldMetadata = (field: CustomFieldInput) => ({
  customFieldName: field.name,
  customFieldType: field.type,
  customFieldRequired: field.required,
  customFieldOptions: field.options,
})

const saveCustomFieldValues = async (createdPiece: any) => {
  if (!createdPiece || !createdPiece.id) {
    return
  }

  const definitionMap = new Map<string, string>()
  const registerDefinitions = (fields: any[]) => {
    if (!Array.isArray(fields)) {
      return
    }
    fields.forEach((field) => {
      if (!field || typeof field !== 'object') {
        return
      }
      const name = typeof field.name === 'string' ? field.name : null
      const id = typeof field.id === 'string' ? field.id : null
      if (name && id && !definitionMap.has(name)) {
        definitionMap.set(name, id)
      }
    })
  }

  registerDefinitions(createdPiece?.typePiece?.pieceCustomFields)
  registerDefinitions(createdPiece?.typeMachinePieceRequirement?.typePiece?.pieceCustomFields)

  const customizeFieldId = (field: CustomFieldInput) => {
    if (field.customFieldId) {
      return field.customFieldId
    }
    if (field.id) {
      return field.id
    }
    return definitionMap.get(field.name) ?? null
  }

  for (const field of customFieldInputs.value) {
    if (!shouldPersistField(field)) {
      continue
    }

    const definitionId = customizeFieldId(field)
    const metadata = definitionId ? undefined : buildCustomFieldMetadata(field)
    const value = formatValueForPersistence(field)

    if (field.customFieldValueId) {
      const result = await updateCustomFieldValue(field.customFieldValueId, { value })
      if (!result.success) {
        toast.showError(`Impossible de mettre à jour le champ personnalisé "${field.name}"`)
      } else if (definitionId && !field.customFieldId) {
        field.customFieldId = definitionId
      }
      continue
    }

    const result = await upsertCustomFieldValue(
      definitionId,
      'piece',
      createdPiece.id,
      value,
      metadata,
    )

    if (!result.success) {
      toast.showError(`Impossible d'enregistrer le champ personnalisé "${field.name}"`)
    } else {
      const createdValue = result.data
      if (createdValue?.id) {
        field.customFieldValueId = createdValue.id
      }
      const resolvedId = createdValue?.customField?.id || definitionId
      if (resolvedId) {
        field.customFieldId = resolvedId
      }
    }
  }
}

const shouldPersistField = (field: CustomFieldInput) => {
  if (field.type === 'boolean') {
    return field.value === 'true' || field.value === 'false'
  }
  return toFieldString(field.value).trim() !== ''
}

const formatValueForPersistence = (field: CustomFieldInput) => {
  if (field.type === 'boolean') {
    return field.value === 'true' ? 'true' : 'false'
  }
  return toFieldString(field.value).trim()
}
</script>
