<script setup>
import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout.vue'
import StatutBadge from '@/Components/Commandes/StatutBadge.vue'
import PrioriteBadge from '@/Components/Commandes/PrioriteBadge.vue'
import HistoriqueTimeline from '@/Components/Commandes/HistoriqueTimeline.vue'
import TransitionModal from '@/Components/Commandes/TransitionModal.vue'
import LignesCommandeForm from '@/Components/Commandes/LignesCommandeForm.vue'
import PiecesJointesSection from '@/Components/Commandes/PiecesJointesSection.vue'
import { Head, Link, usePage } from '@inertiajs/vue3'
import { ref, computed } from 'vue'

const props = defineProps({
    commande:               Object,
    transitionsDisponibles: Array,
})

const page = usePage()
const statuts = page.props.config?.statuts ?? {}

const showTransitionModal = ref(false)
const targetStatut = ref(null)

function openTransition(statut) {
    targetStatut.value = statut
    showTransitionModal.value = true
}

function formatDate(d, withTime = false) {
    if (!d) return '—'
    const opts = withTime
        ? { day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit' }
        : { day: '2-digit', month: '2-digit', year: 'numeric' }
    return new Intl.DateTimeFormat('fr-FR', opts).format(new Date(d))
}

function formatCurrency(v) {
    if (v == null) return '—'
    return new Intl.NumberFormat('fr-FR', { style: 'currency', currency: 'EUR' }).format(v)
}

const transitionColors = {
    en_attente_validation: 'bg-yellow-50 border-yellow-300 text-yellow-800 hover:bg-yellow-100',
    validee:               'bg-blue-50 border-blue-300 text-blue-800 hover:bg-blue-100',
    commandee:             'bg-indigo-50 border-indigo-300 text-indigo-800 hover:bg-indigo-100',
    brouillon:             'bg-gray-50 border-gray-300 text-gray-700 hover:bg-gray-100',
    partiellement_recue:   'bg-orange-50 border-orange-300 text-orange-800 hover:bg-orange-100',
    recue_complete:        'bg-green-50 border-green-300 text-green-800 hover:bg-green-100',
    cloturee:              'bg-slate-50 border-slate-300 text-slate-700 hover:bg-slate-100',
    annulee:               'bg-red-50 border-red-300 text-red-800 hover:bg-red-100',
}
</script>

<template>
    <Head :title="commande.numero_commande" />
    <AuthenticatedLayout>
        <template #header>
            <div class="flex flex-wrap items-center justify-between gap-4">
                <div class="flex items-center gap-3">
                    <Link :href="route('commandes.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>
                    <div>
                        <h1 class="text-xl font-semibold text-gray-900">{{ commande.numero_commande }}</h1>
                        <p class="text-sm text-gray-500">{{ commande.objet }}</p>
                    </div>
                    <StatutBadge :statut="commande.statut" size="lg" />
                    <PrioriteBadge :priorite="commande.priorite" />
                </div>
                <div class="flex items-center gap-2">
                    <a :href="route('commandes.pdf', commande.id)" target="_blank" rel="noopener noreferrer"
                        class="rounded-lg bg-gray-800 px-4 py-2 text-sm font-medium text-white hover:bg-gray-700 transition-colors 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 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                        </svg>
                        PDF
                    </a>
                    <Link v-if="['brouillon','en_attente_validation'].includes(commande.statut)"
                        :href="route('commandes.edit', commande.id)"
                        class="rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 transition-colors">
                        Modifier
                    </Link>
                </div>
            </div>
        </template>

        <div class="grid gap-6 lg:grid-cols-3">
            <!-- Left column (2/3) -->
            <div class="space-y-6 lg:col-span-2">
                <!-- Infos générales -->
                <div class="rounded-xl bg-white p-5 shadow-sm border border-gray-100">
                    <h2 class="mb-4 text-sm font-semibold uppercase tracking-wide text-gray-500">Informations générales</h2>
                    <div class="grid gap-4 sm:grid-cols-2">
                        <div>
                            <p class="text-xs text-gray-500">Service demandeur</p>
                            <p class="mt-0.5 font-medium text-gray-900">{{ commande.service?.nom ?? '—' }}</p>
                        </div>
                        <div>
                            <p class="text-xs text-gray-500">Fournisseur</p>
                            <p class="mt-0.5 font-medium text-gray-900">{{ commande.fournisseur?.nom ?? '—' }}</p>
                        </div>
                        <div>
                            <p class="text-xs text-gray-500">Demandeur</p>
                            <p class="mt-0.5 font-medium text-gray-900">{{ commande.demandeur?.name ?? '—' }}</p>
                        </div>
                        <div>
                            <p class="text-xs text-gray-500">Validateur</p>
                            <p class="mt-0.5 font-medium text-gray-900">{{ commande.validateur?.name ?? '—' }}</p>
                        </div>
                        <div>
                            <p class="text-xs text-gray-500">Date de demande</p>
                            <p class="mt-0.5 font-medium text-gray-900">{{ formatDate(commande.date_demande) }}</p>
                        </div>
                        <div>
                            <p class="text-xs text-gray-500">Date souhaitée</p>
                            <p class="mt-0.5 font-medium" :class="commande.est_en_retard ? 'text-red-600' : 'text-gray-900'">
                                {{ formatDate(commande.date_souhaitee) }}
                                <span v-if="commande.est_en_retard" class="ml-1 text-xs">⚠ En retard</span>
                            </p>
                        </div>
                        <div v-if="commande.date_commande">
                            <p class="text-xs text-gray-500">Date commande</p>
                            <p class="mt-0.5 font-medium text-gray-900">{{ formatDate(commande.date_commande, true) }}</p>
                        </div>
                        <div v-if="commande.date_livraison_prevue">
                            <p class="text-xs text-gray-500">Livraison prévue</p>
                            <p class="mt-0.5 font-medium text-gray-900">{{ formatDate(commande.date_livraison_prevue) }}</p>
                        </div>
                        <div v-if="commande.reference_fournisseur">
                            <p class="text-xs text-gray-500">Référence fournisseur</p>
                            <p class="mt-0.5 font-medium text-gray-900">{{ commande.reference_fournisseur }}</p>
                        </div>
                        <div v-if="commande.imputation_budgetaire">
                            <p class="text-xs text-gray-500">Imputation budgétaire</p>
                            <p class="mt-0.5 font-medium text-gray-900">{{ commande.imputation_budgetaire }}</p>
                        </div>
                    </div>
                    <!-- Montants -->
                    <div class="mt-4 flex gap-6 rounded-lg bg-gray-50 p-4">
                        <div>
                            <p class="text-xs text-gray-500">Montant HT</p>
                            <p class="text-lg font-bold text-gray-900">{{ formatCurrency(commande.montant_ht) }}</p>
                        </div>
                        <div>
                            <p class="text-xs text-gray-500">Montant TTC</p>
                            <p class="text-lg font-bold text-blue-700">{{ formatCurrency(commande.montant_ttc) }}</p>
                        </div>
                    </div>
                </div>

                <!-- Lignes de commande -->
                <div class="rounded-xl bg-white p-5 shadow-sm border border-gray-100">
                    <h2 class="mb-4 text-sm font-semibold uppercase tracking-wide text-gray-500">Lignes de commande</h2>
                    <LignesCommandeForm
                        :model-value="commande.lignes"
                        :categories="[]"
                        :articles="[]"
                        :readonly="true"
                        :show-received="['commandee','partiellement_recue','recue_complete','cloturee'].includes(commande.statut)" />
                </div>

                <!-- Notes -->
                <div v-if="commande.description || commande.justification || commande.notes || commande.notes_fournisseur"
                    class="rounded-xl bg-white p-5 shadow-sm border border-gray-100">
                    <h2 class="mb-4 text-sm font-semibold uppercase tracking-wide text-gray-500">Notes et commentaires</h2>
                    <div class="space-y-3">
                        <div v-if="commande.description">
                            <p class="text-xs font-medium text-gray-500">Description</p>
                            <p class="mt-1 text-sm text-gray-700 whitespace-pre-wrap">{{ commande.description }}</p>
                        </div>
                        <div v-if="commande.justification">
                            <p class="text-xs font-medium text-gray-500">Justification</p>
                            <p class="mt-1 text-sm text-gray-700 whitespace-pre-wrap">{{ commande.justification }}</p>
                        </div>
                        <div v-if="commande.notes">
                            <p class="text-xs font-medium text-gray-500">Notes internes</p>
                            <p class="mt-1 text-sm text-gray-700 whitespace-pre-wrap">{{ commande.notes }}</p>
                        </div>
                        <div v-if="commande.notes_fournisseur">
                            <p class="text-xs font-medium text-gray-500">Notes fournisseur</p>
                            <p class="mt-1 text-sm text-gray-700 whitespace-pre-wrap">{{ commande.notes_fournisseur }}</p>
                        </div>
                    </div>
                </div>

                <!-- Pièces jointes -->
                <div class="rounded-xl bg-white p-5 shadow-sm border border-gray-100">
                    <PiecesJointesSection :commande="commande" />
                </div>
            </div>

            <!-- Right column (1/3) -->
            <div class="space-y-6">
                <!-- Transitions -->
                <div v-if="transitionsDisponibles.length" class="rounded-xl bg-white p-5 shadow-sm border border-gray-100">
                    <h2 class="mb-3 text-sm font-semibold uppercase tracking-wide text-gray-500">Actions</h2>
                    <div class="space-y-2">
                        <button v-for="statut in transitionsDisponibles" :key="statut"
                            @click="openTransition(statut)"
                            :class="['w-full rounded-lg border px-4 py-2.5 text-sm font-medium transition-colors text-left', transitionColors[statut] ?? 'bg-gray-50 border-gray-300 text-gray-700 hover:bg-gray-100']">
                            → {{ statuts[statut] ?? statut }}
                        </button>
                    </div>
                </div>

                <!-- Historique -->
                <div class="rounded-xl bg-white p-5 shadow-sm border border-gray-100">
                    <h2 class="mb-4 text-sm font-semibold uppercase tracking-wide text-gray-500">Historique</h2>
                    <HistoriqueTimeline :historique="commande.historique" />
                </div>
            </div>
        </div>

        <TransitionModal :show="showTransitionModal" :commande="commande" :target-statut="targetStatut"
            @close="showTransitionModal = false" />
    </AuthenticatedLayout>
</template>
