/**
 * Machine creation page – orchestration composable.
 *
 * Simplified: no more TypeMachine / skeleton system.
 * Supports direct creation or cloning from an existing machine.
 */

import { ref, reactive, onMounted } from 'vue'
import { useMachines } from '~/composables/useMachines'
import { useSites } from '~/composables/useSites'
import { humanizeError } from '~/shared/utils/errorMessages'

export function useMachineCreatePage() {
  // ---------------------------------------------------------------------------
  // Composable calls
  // ---------------------------------------------------------------------------

  const { machines, loadMachines, createMachine, cloneMachine } = useMachines()
  const { sites, loadSites } = useSites()

  // ---------------------------------------------------------------------------
  // Local state
  // ---------------------------------------------------------------------------

  const submitting = ref(false)
  const loading = ref(true)

  /** Persistent error shown inline in the form (e.g. duplicate name on the same site). */
  const createError = ref<string | null>(null)

  const newMachine = reactive({
    name: '',
    siteId: '',
    reference: '',
    cloneFromMachineId: '',
    // 'full' = clone complet (composants/pièces concrets) ; 'structure' = catégories
    // uniquement (slots à compléter).
    cloneMode: 'full' as 'full' | 'structure',
  })

  // ---------------------------------------------------------------------------
  // Machine creation
  // ---------------------------------------------------------------------------

  const finalizeMachineCreation = async () => {
    if (submitting.value) return

    createError.value = null

    if (!newMachine.name?.trim()) {
      createError.value = 'Merci de renseigner un nom pour la machine.'
      return
    }

    submitting.value = true
    try {
      let result: any

      if (newMachine.cloneFromMachineId) {
        result = await cloneMachine(newMachine.cloneFromMachineId, {
          name: newMachine.name,
          siteId: newMachine.siteId,
          mode: newMachine.cloneMode,
          ...(newMachine.reference ? { reference: newMachine.reference } : {}),
        })
      } else {
        result = await createMachine({
          name: newMachine.name,
          siteId: newMachine.siteId || undefined,
          reference: newMachine.reference || undefined,
        } as any)
      }

      if (result.success) {
        const machineId = result.data?.id
          || (result.data?.machine as any)?.id
          || null

        newMachine.name = ''
        newMachine.siteId = ''
        newMachine.reference = ''
        newMachine.cloneFromMachineId = ''

        if (machineId) {
          await navigateTo(`/machine/${machineId}`)
        } else {
          await navigateTo('/machines')
        }
      } else if (result.error) {
        createError.value = humanizeError(result.error)
      }
    } catch (error: any) {
      createError.value = humanizeError(error.message)
    } finally {
      submitting.value = false
    }
  }

  // ---------------------------------------------------------------------------
  // Lifecycle
  // ---------------------------------------------------------------------------

  onMounted(async () => {
    loading.value = true
    try {
      await Promise.all([
        loadSites(),
        loadMachines(),
      ])
    } finally {
      loading.value = false
    }
  })

  // ---------------------------------------------------------------------------
  // Public API
  // ---------------------------------------------------------------------------

  return {
    // State
    newMachine,
    sites,
    machines,
    submitting,
    loading,
    createError,

    // Actions
    finalizeMachineCreation,
  }
}
