<script setup>
import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout.vue'
import { Head, Link, useForm } from '@inertiajs/vue3'
import { ref } from 'vue'

const props = defineProps({
    asset:     Object,
    communes:  Array,
    commandes: Array,
})

const isEdit = !!props.asset

const form = useForm({
    nom:               props.asset?.nom || '',
    type:              props.asset?.type || '',
    marque:            props.asset?.marque || '',
    modele:            props.asset?.modele || '',
    numero_serie:      props.asset?.numero_serie || '',
    emplacement:       props.asset?.emplacement || '',
    commune_id:        props.asset?.commune_id || '',
    date_achat:        props.asset?.date_achat ? props.asset.date_achat.substring(0, 10) : '',
    date_fin_garantie: props.asset?.date_fin_garantie ? props.asset.date_fin_garantie.substring(0, 10) : '',
    statut:            props.asset?.statut || 'en_service',
    commande_id:       props.asset?.commande_id || '',
    code_ean:          props.asset?.code_ean || '',
    notes:             props.asset?.notes || '',
})

const isSearchingEan = ref(false)
const eanError = ref('')
const eanSuccess = ref('')

async function fetchEanDetails() {
    if (!form.code_ean) return

    isSearchingEan.value = true
    eanError.value = ''
    eanSuccess.value = ''

    try {
        const response = await fetch(`/api/ean-lookup/${form.code_ean}`)
        
        if (!response.ok) {
           throw new Error('API limit or error')
        }

        const data = await response.json()

        if (data.code === 'OK' && data.items && data.items.length > 0) {
            const item = data.items[0]
            
            if (item.title && !form.nom) form.nom = item.title
            if (item.brand && !form.marque) form.marque = item.brand
            if (item.model && !form.modele) form.modele = item.model
            
            // Infer type loosely
            if (!form.type && item.category) {
                const cat = item.category.toLowerCase()
                if (cat.includes('server') || cat.includes('serveur')) form.type = 'Serveur'
                else if (cat.includes('switch') || cat.includes('router') || cat.includes('network')) form.type = 'Switch'
                else if (cat.includes('storage') || cat.includes('nas')) form.type = 'NAS'
                else form.type = item.category.split('>').pop().trim()
            }
            
            eanSuccess.value = "Informations pré-remplies avec succès."
        } else {
            eanError.value = 'Aucun produit trouvé pour ce code.'
        }
    } catch (error) {
        eanError.value = 'Erreur API ou limite atteinte.'
    } finally {
        isSearchingEan.value = false
    }
}

function submit() {
    if (isEdit) {
        form.put(route('assets.update', props.asset.id))
    } else {
        form.post(route('assets.store'))
    }
}
</script>

<template>
    <Head :title="isEdit ? 'Modifier Asset' : 'Nouvel Asset'" />
    <AuthenticatedLayout>
        <template #header>
            <div class="flex items-center gap-3">
                <Link :href="route('assets.index')" class="text-gray-400 hover:text-gray-600 transition-colors">
                    <svg class="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" />
                    </svg>
                </Link>
                <h1 class="text-xl font-semibold text-gray-900">{{ isEdit ? 'Modifier l\'équipement' : 'Ajouter un équipement' }}</h1>
            </div>
        </template>

        <div class="max-w-4xl pb-12">
            <form @submit.prevent="submit" class="space-y-6">
                <!-- Autocomplétion EAN -->
                <div class="rounded-xl bg-indigo-50 p-6 shadow-sm border border-indigo-100 mb-6">
                    <h2 class="mb-3 text-sm font-semibold uppercase tracking-wide text-indigo-800 flex items-center gap-2">
                        <svg class="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v1m6 11h2m-6 0h-2v4m0-11v3m0 0h.01M12 12h4.01M16 20h4M4 12h4m12 0h.01M5 8h2a1 1 0 001-1V5a1 1 0 00-1-1H5a1 1 0 00-1 1v2a1 1 0 001 1zm14 0h2a1 1 0 001-1V5a1 1 0 00-1-1h-2a1 1 0 00-1 1v2a1 1 0 001 1zM5 20h2a1 1 0 001-1v-2a1 1 0 00-1-1H5a1 1 0 00-1 1v2a1 1 0 001 1z" />
                        </svg>
                        Pré-remplissage Magique par Code-Barres
                    </h2>
                    <div class="flex items-end gap-4">
                        <div class="flex-1">
                            <label class="block text-sm font-medium text-indigo-700">Scanner ou Saisir le Code EAN/UPC</label>
                            <input v-model="form.code_ean" type="text" @keyup.enter.prevent="fetchEanDetails"
                                class="mt-1 block w-full rounded-lg border-indigo-200 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm font-mono" placeholder="ex: 0884116301292" />
                        </div>
                        <button type="button" @click="fetchEanDetails" :disabled="isSearchingEan || !form.code_ean"
                            class="rounded-lg bg-indigo-600 px-4 py-2 mt-1 text-sm font-medium text-white shadow hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 disabled:bg-indigo-300 transition-colors flex items-center gap-2">
                            <svg v-if="isSearchingEan" class="animate-spin h-4 w-4 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                                <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                                <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                            </svg>
                            Rechercher
                        </button>
                    </div>
                    <p v-if="eanError" class="mt-2 text-xs font-semibold text-red-600">{{ eanError }}</p>
                    <p v-if="eanSuccess" class="mt-2 text-xs font-semibold text-green-600">{{ eanSuccess }}</p>
                </div>

                <!-- Informations de base -->
                <div class="rounded-xl bg-white p-6 shadow-sm border border-gray-100">
                    <h2 class="mb-5 text-sm font-semibold uppercase tracking-wide text-gray-500 font-bold">Identification de l'asset</h2>
                    
                    <div class="grid gap-6 sm:grid-cols-2">
                        <div class="sm:col-span-1">
                            <label class="block text-sm font-medium text-gray-700 font-bold">Nom / Hostname</label>
                            <input v-model="form.nom" type="text" required class="mt-1 block w-full rounded-lg border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm" placeholder="ex: SRV-SQL-01" />
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-gray-700 font-bold">Type de matériel</label>
                            <input v-model="form.type" list="asset-types" required class="mt-1 block w-full rounded-lg border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm" placeholder="ex: Serveur" />
                            <datalist id="asset-types">
                                <option value="Serveur" />
                                <option value="Switch" />
                                <option value="NAS" />
                                <option value="Baie de stockage" />
                                <option value="Onduleur" />
                                <option value="Firewall" />
                                <option value="Cœur de réseau" />
                            </datalist>
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-gray-700">Marque</label>
                            <input v-model="form.marque" type="text" class="mt-1 block w-full rounded-lg border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm" placeholder="ex: Dell" />
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-gray-700">Modèle</label>
                            <input v-model="form.modele" type="text" class="mt-1 block w-full rounded-lg border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm" placeholder="ex: PowerEdge R640" />
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-gray-700">Numéro de série / SN / Tag</label>
                            <input v-model="form.numero_serie" type="text" class="mt-1 block w-full rounded-lg border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm font-mono" placeholder="ex: ABC123D" />
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-gray-700">Statut actuel</label>
                            <select v-model="form.statut" required class="mt-1 block w-full rounded-lg border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm">
                                <option value="en_service">En service</option>
                                <option value="hors_service">Hors service</option>
                                <option value="en_reparation">En réparation</option>
                                <option value="stock">En stock / Spare</option>
                            </select>
                        </div>
                    </div>
                </div>

                <!-- Emplacement et Commune -->
                <div class="rounded-xl bg-white p-6 shadow-sm border border-gray-100">
                    <h2 class="mb-5 text-sm font-semibold uppercase tracking-wide text-gray-500 font-bold">Localisation et Affectation</h2>
                    
                    <div class="grid gap-6 sm:grid-cols-2">
                        <div>
                            <label class="block text-sm font-medium text-gray-700">Ville / Commune</label>
                            <select v-model="form.commune_id" class="mt-1 block w-full rounded-lg border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm">
                                <option value="">Infrastructure Globale (Agglo)</option>
                                <option v-for="c in communes" :key="c.id" :value="c.id">{{ c.nom }}</option>
                            </select>
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-gray-700">Emplacement précis / Site</label>
                            <input v-model="form.emplacement" type="text" class="mt-1 block w-full rounded-lg border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm" placeholder="ex: Datacenter Local Lyon - Rack A2 - 12U" />
                        </div>
                    </div>
                </div>

                <!-- Dates et Garanties -->
                <div class="rounded-xl bg-white p-6 shadow-sm border border-gray-100">
                    <h2 class="mb-5 text-sm font-semibold uppercase tracking-wide text-gray-500 font-bold">Cycle de vie & Garanties</h2>
                    
                    <div class="grid gap-6 sm:grid-cols-2">
                        <div>
                            <label class="block text-sm font-medium text-gray-700">Date d'achat / mise en service</label>
                            <input v-model="form.date_achat" type="date" class="mt-1 block w-full rounded-lg border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm" />
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-gray-700 font-bold">Fin de garantie constructeur</label>
                            <input v-model="form.date_fin_garantie" type="date" required class="mt-1 block w-full rounded-lg border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm" />
                            <p class="mt-1 text-xs text-gray-500">Cette date sera affichée dans le calendrier global.</p>
                        </div>
                    </div>
                </div>

                <!-- Lien Commande -->
                <div class="rounded-xl bg-white p-6 shadow-sm border border-gray-100">
                    <h2 class="mb-5 text-sm font-semibold uppercase tracking-wide text-gray-500 font-bold">Achat & Commande</h2>
                    <div>
                        <label class="block text-sm font-medium text-gray-700">Commande associée (optionnel)</label>
                        <select v-model="form.commande_id" class="mt-1 block w-full rounded-lg border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm">
                            <option value="">Aucune commande liée</option>
                            <option v-for="cmd in commandes" :key="cmd.id" :value="cmd.id">
                                N° {{ cmd.numero_commande ?? 'Sans-N' }} - {{ cmd.objet }}
                            </option>
                        </select>
                        <p class="mt-1 text-xs text-gray-500">Permet de retrouver l'origine de l'achat et les justificatifs.</p>
                    </div>
                </div>

                <!-- Notes -->
                <div class="rounded-xl bg-white p-6 shadow-sm border border-gray-100">
                    <label class="block text-sm font-medium text-gray-700 font-bold mb-2">Notes techniques / Configuration</label>
                    <textarea v-model="form.notes" rows="4" class="block w-full rounded-lg border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm" placeholder="IP, VLANs, rôles du serveur..."></textarea>
                </div>

                <div class="flex items-center justify-end gap-3">
                    <Link :href="route('assets.index')" class="text-sm font-medium text-gray-600 hover:text-gray-900 transition-colors">Annuler</Link>
                    <button type="submit" :disabled="form.processing"
                        class="rounded-lg bg-indigo-600 px-6 py-2.5 text-sm font-semibold text-white shadow-sm hover:bg-indigo-700 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600 disabled:opacity-50 transition-colors">
                        {{ isEdit ? 'Enregistrer les modifications' : 'Ajouter l\'équipement' }}
                    </button>
                    <button v-if="isEdit" type="button" @click="confirmDelete"
                        class="ml-4 rounded-lg bg-red-50 px-4 py-2 text-sm font-medium text-red-600 hover:bg-red-100 transition-colors">
                        Supprimer
                    </button>
                </div>
            </form>
        </div>
    </AuthenticatedLayout>
</template>

<script>
import { router } from '@inertiajs/vue3'

export default {
    methods: {
        confirmDelete() {
            if (confirm('Êtes-vous sûr de vouloir supprimer cet équipement ?')) {
                router.delete(route('assets.destroy', this.asset.id))
            }
        }
    }
}
</script>
