<template>
  <main class="container mx-auto px-6 py-10">
    <div v-if="loading" class="flex flex-col items-center gap-4 py-20 text-center">
      <span class="loading loading-spinner loading-lg" aria-hidden="true" />
      <p class="text-sm text-base-content/70">Chargement du composant…</p>
    </div>

    <div v-else-if="!component" class="max-w-xl mx-auto">
      <div class="alert alert-error shadow-lg">
        <div>
          <h2 class="font-semibold text-lg">Composant introuvable</h2>
          <p class="text-sm text-base-content/80">
            Nous n'avons pas pu retrouver le composant demandé. Il a peut-être été supprimé.
          </p>
        </div>
      </div>
      <NuxtLink to="/component-catalog" class="btn btn-primary mt-6">
        Retour au catalogue
      </NuxtLink>
    </div>

    <section v-else class="card border border-base-200 bg-base-100 shadow-sm max-w-5xl mx-auto">
      <div class="card-body space-y-6">
        <header class="flex flex-col gap-2 md:flex-row md:items-center md:justify-between">
          <div>
            <h1 class="text-3xl font-semibold text-base-content">Modifier le composant</h1>
            <p class="text-sm text-base-content/70">
              Mettez à jour les informations du composant et ses champs personnalisés.
            </p>
          </div>
          <NuxtLink to="/component-catalog" class="btn btn-ghost btn-sm md:btn-md self-start">
            Retour au catalogue
          </NuxtLink>
        </header>

        <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 composant</span>
            </label>
            <select
              v-model="selectedTypeId"
              class="select select-bordered select-sm md:select-md"
              disabled
            >
              <option value="">Sélectionner une catégorie</option>
              <option
                v-for="type in componentTypeList"
                :key="type.id"
                :value="type.id"
              >
                {{ type.name }}
              </option>
            </select>
            <p class="text-xs text-base-content/60 mt-1">
              La catégorie d'origine ne peut pas être modifiée depuis cette page.
            </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 du composant</span>
            </label>
            <input
              v-model="editionForm.name"
              type="text"
              class="input input-bordered input-sm md:input-md"
              :disabled="saving"
              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="editionForm.reference"
              type="text"
              class="input input-bordered input-sm md:input-md"
              :disabled="saving"
              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="editionForm.constructeurId"
              class="w-full"
              :disabled="saving"
              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="editionForm.prix"
              type="number"
              step="0.01"
              min="0"
              class="input input-bordered input-sm md:input-md"
              :disabled="saving"
              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 contraintes du composant.' }}
              </p>
            </div>
            <span class="badge badge-outline">{{ formatStructurePreview(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-4 text-sm text-base-content/80">
              <div v-if="getStructureCustomFields(selectedType.structure).length" class="space-y-2">
                <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.key || field.name"
                  >
                    <span class="font-medium">{{ field.key || field.name }}</span>
                    <span v-if="field.value !== undefined && field.value !== null"> : {{ field.value }}</span>
                  </li>
                </ul>
              </div>

              <div v-if="getStructurePieces(selectedType.structure).length" class="space-y-2">
                <h3 class="font-semibold text-sm text-base-content">Pièces imposées</h3>
                <ul class="list-disc list-inside space-y-1">
                  <li
                    v-for="(piece, index) in getStructurePieces(selectedType.structure)"
                    :key="piece.role || piece.typePieceId || piece.familyCode || index"
                  >
                    {{ resolvePieceLabel(piece) }}
                  </li>
                </ul>
              </div>

              <div v-if="getStructureSubcomponents(selectedType.structure).length" class="space-y-2">
                <h3 class="font-semibold text-sm text-base-content">Sous-composants</h3>
                <ul class="list-disc list-inside space-y-1">
                  <li
                    v-for="(subcomponent, index) in getStructureSubcomponents(selectedType.structure)"
                    :key="subcomponent.alias || subcomponent.typeComposantId || subcomponent.familyCode || index"
                  >
                    {{ resolveSubcomponentLabel(subcomponent) }}
                  </li>
                </ul>
              </div>

              <p
                v-if="!getStructureCustomFields(selectedType.structure).length && !getStructurePieces(selectedType.structure).length && !getStructureSubcomponents(selectedType.structure).length"
                class="text-xs text-gray-500"
              >
                Ce squelette ne définit pas encore de pièces, sous-composants ou valeurs par défaut.
              </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">
              Mettez à jour les valeurs propres à ce composant.
            </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="saving"
              >
              <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="saving"
              >
              <select
                v-else-if="field.type === 'select'"
                v-model="field.value"
                class="select select-bordered select-sm md:select-md"
                :required="field.required"
                :disabled="saving"
              >
                <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="saving"
                >
                <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="saving"
              >
              <input
                v-else
                v-model="field.value"
                type="text"
                class="input input-bordered input-sm md:input-md"
                :required="field.required"
                :disabled="saving"
              >
            </div>
          </div>
        </div>

        <div class="flex flex-col gap-3 md:flex-row md:justify-end">
          <NuxtLink to="/component-catalog" class="btn btn-ghost" :class="{ 'btn-disabled': saving }">
            Annuler
          </NuxtLink>
          <button type="button" class="btn btn-primary" :disabled="!canSubmit" @click="submitEdition">
            <span v-if="saving" class="loading loading-spinner loading-sm mr-2" />
            Enregistrer les modifications
          </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 { useComponentTypes } from '~/composables/useComponentTypes'
import { useComposants } from '~/composables/useComposants'
import { useCustomFields } from '~/composables/useCustomFields'
import { useApi } from '~/composables/useApi'
import { useToast } from '~/composables/useToast'
import { formatStructurePreview } from '~/shared/modelUtils'
import type { ComponentModelStructure } from '~/shared/types/inventory'
import type { ModelType } from '~/services/modelTypes'

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

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

const route = useRoute()
const router = useRouter()
const { get } = useApi()
const { componentTypes, loadComponentTypes } = useComponentTypes()
const { updateComposant } = useComposants()
const { upsertCustomFieldValue, updateCustomFieldValue } = useCustomFields()
const toast = useToast()

const component = ref<any | null>(null)
const loading = ref(true)
const saving = ref(false)

const selectedTypeId = ref<string>('')
const editionForm = reactive({
  name: '' as string,
  reference: '' as string,
  constructeurId: null as string | null,
  prix: '' as string,
})

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

const componentTypeList = computed<ComponentCatalogType[]>(() =>
  (componentTypes.value || [])
    .filter((item: any) => item?.category === 'COMPONENT') as ComponentCatalogType[],
)

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

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

const canSubmit = computed(() => Boolean(
  component.value &&
  editionForm.name &&
  requiredCustomFieldsFilled.value &&
  !saving.value,
))

const fetchComponent = async () => {
  const id = route.params.id
  if (!id || typeof id !== 'string') {
    component.value = null
    return
  }
  const result = await get(`/composants/${id}`)
  component.value = result.success ? result.data : null
}

let initialized = false

watch(
  [component, selectedType],
  ([currentComponent, currentType]) => {
    if (!currentComponent || initialized) {
      return
    }

    selectedTypeId.value = currentComponent.typeComposantId || ''

    editionForm.name = currentComponent.name || ''
    editionForm.reference = currentComponent.reference || ''
    editionForm.constructeurId = currentComponent.constructeur?.id || currentComponent.constructeurId || null
    editionForm.prix = currentComponent.prix !== null && currentComponent.prix !== undefined ? String(currentComponent.prix) : ''

    customFieldInputs.value = buildCustomFieldInputs(
      currentType?.structure ?? null,
      currentComponent.customFieldValues,
    )

    initialized = true
  },
  { immediate: true },
)

watch(selectedType, (currentType) => {
  if (!component.value || !currentType) {
    return
  }
  customFieldInputs.value = buildCustomFieldInputs(
    currentType.structure,
    component.value.customFieldValues,
  )
})

const submitEdition = async () => {
  if (!component.value) {
    return
  }

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

  const payload: Record<string, any> = {
    name: editionForm.name.trim(),
  }

  const reference = editionForm.reference.trim()
  payload.reference = reference ? reference : null
  payload.constructeurId = editionForm.constructeurId || null

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

  saving.value = true
  try {
    const result = await updateComposant(component.value.id, payload)
    if (result.success) {
      const updatedComponent = result.data
      await saveCustomFieldValues(updatedComponent)
      await router.push('/component-catalog')
    }
  } catch (error: any) {
    toast.showError(error?.message || 'Erreur lors de la mise à jour du composant')
  } finally {
    saving.value = false
  }
}

const buildCustomFieldInputs = (
  structure: ComponentModelStructure | null,
  values: any[] | null,
): CustomFieldInput[] => {
  const definitions = normalizeCustomFieldInputs(structure)
  const valueList = Array.isArray(values) ? values : []

  const mapById = new Map<string, any>()
  const mapByName = new Map<string, any>()

  valueList.forEach((entry) => {
    if (!entry || typeof entry !== 'object') {
      return
    }
    const fieldId = entry.customField?.id || entry.customFieldId || null
    if (fieldId) {
      mapById.set(fieldId, entry)
    }
    const fieldName = entry.customField?.name || entry.name || entry.key || null
    if (fieldName) {
      mapByName.set(fieldName, entry)
    }
  })

  const resolved: CustomFieldInput[] = definitions.map((definition) => {
    const definitionId = definition.customFieldId || definition.id || null
    const matched = (definitionId ? mapById.get(definitionId) : null) || mapByName.get(definition.name)

    if (!matched) {
      return {
        ...definition,
        customFieldId: definition.customFieldId || definition.id,
        customFieldValueId: null,
      }
    }

    const resolvedValue = matched.value ?? ''
    return {
      ...definition,
      customFieldId: matched.customField?.id || definition.customFieldId || definition.id,
      customFieldValueId: matched.id ?? null,
      value: formatDefaultValue(definition.type, resolvedValue),
    }
  })

  return resolved
}

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

const normalizeCustomFieldInputs = (structure: ComponentModelStructure | 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 getStructureCustomFields = (structure: ComponentModelStructure | null) => {
  return Array.isArray(structure?.customFields) ? structure.customFields : []
}

const getStructurePieces = (structure: ComponentModelStructure | null) => {
  return Array.isArray(structure?.pieces) ? structure.pieces : []
}

const getStructureSubcomponents = (structure: ComponentModelStructure | null) => {
  if (Array.isArray(structure?.subcomponents)) {
    return structure.subcomponents
  }
  const legacy = (structure as any)?.subComponents
  return Array.isArray(legacy) ? legacy : []
}

const resolvePieceLabel = (piece: Record<string, any>) => {
  const parts: string[] = []
  if (piece.role) {
    parts.push(piece.role)
  }
  if (piece.typePiece?.name) {
    parts.push(piece.typePiece.name)
  } else if (piece.typePieceLabel) {
    parts.push(piece.typePieceLabel)
  } else if (piece.familyCode) {
    parts.push(piece.familyCode)
  } else if (piece.typePieceId) {
    parts.push(`#${piece.typePieceId}`)
  }
  return parts.length ? parts.join(' • ') : 'Pièce'
}

const resolveSubcomponentLabel = (node: Record<string, any>) => {
  const parts: string[] = []
  if (node.alias) {
    parts.push(node.alias)
  }
  if (node.typeComposant?.name) {
    parts.push(node.typeComposant.name)
  } else if (node.typeComposantLabel) {
    parts.push(node.typeComposantLabel)
  } else if (node.familyCode) {
    parts.push(node.familyCode)
  } else if (node.typeComposantId) {
    parts.push(`#${node.typeComposantId}`)
  }

  const childCount = Array.isArray(node.subcomponents)
    ? node.subcomponents.length
    : Array.isArray(node.subComponents)
      ? node.subComponents.length
      : 0
  if (childCount) {
    parts.push(`${childCount} sous-composant(s)`)
  }
  return parts.length ? parts.join(' • ') : 'Sous-composant'
}

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

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

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

const saveCustomFieldValues = async (updatedComponent: any) => {
  if (!updatedComponent || !updatedComponent.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(updatedComponent?.typeComposant?.customFields)
  registerDefinitions(updatedComponent?.typeMachineComponentRequirement?.typeComposant?.customFields)

  const resolveDefinitionId = (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 = resolveDefinitionId(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,
      'composant',
      updatedComponent.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
      }
    }
  }
}

onMounted(async () => {
  await Promise.allSettled([loadComponentTypes(), fetchComponent()])
  loading.value = false
})
</script>
