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

const props = defineProps({
    order: Object,
});

const form = useForm({
    status: props.order.status,
    tracking_number: props.order.tracking_number || '',
    tracking_url: props.order.tracking_url || '',
    admin_notes: props.order.admin_notes || '',
});

const showStatusModal = ref(false);

const updateStatus = () => {
    form.post(route('admin.store.orders.status', props.order.id), {
        onSuccess: () => showStatusModal.value = false,
    });
};

const markAsPaid = () => {
    if (confirm('¿Marcar este pedido como pagado?')) {
        router.post(route('admin.store.orders.paid', props.order.id));
    }
};

const formatCurrency = (value) => {
    return 'RD$' + new Intl.NumberFormat('es-DO', { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(value);
};

const formatDate = (date) => {
    return new Date(date).toLocaleDateString('es-DO', { day: '2-digit', month: 'long', year: 'numeric', hour: '2-digit', minute: '2-digit' });
};

const statusColors = {
    pending: 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400',
    processing: 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400',
    shipped: 'bg-indigo-100 text-indigo-800 dark:bg-indigo-900/30 dark:text-indigo-400',
    delivered: 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400',
    cancelled: 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400',
    refunded: 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-400',
};

const statusLabels = {
    pending: 'Pendiente',
    processing: 'Procesando',
    shipped: 'Enviado',
    delivered: 'Entregado',
    cancelled: 'Cancelado',
    refunded: 'Reembolsado',
};
</script>

<template>
    <Head :title="'Pedido ' + order.order_number" />

    <AdminLayout>
        <div class="py-6">
            <!-- Header -->
            <div class="mb-8 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
                <div>
                    <nav class="flex items-center text-sm text-gray-500 dark:text-gray-400 mb-2">
                        <Link :href="route('admin.store.orders.index')" class="hover:text-blue-600">Pedidos</Link>
                        <span class="mx-2">/</span>
                        <span>{{ order.order_number }}</span>
                    </nav>
                    <h1 class="text-2xl font-bold text-gray-900 dark:text-white">{{ order.order_number }}</h1>
                    <p class="text-gray-500">{{ formatDate(order.created_at) }}</p>
                </div>
                <div class="flex gap-3">
                    <button
                        v-if="order.payment_status !== 'paid'"
                        @click="markAsPaid"
                        class="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition"
                    >
                        Marcar como pagado
                    </button>
                    <button
                        @click="showStatusModal = true"
                        class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition"
                    >
                        Actualizar estado
                    </button>
                </div>
            </div>

            <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
                <!-- Order Details -->
                <div class="lg:col-span-2 space-y-6">
                    <!-- Items -->
                    <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 overflow-hidden">
                        <div class="p-4 border-b dark:border-gray-700">
                            <h2 class="font-semibold text-gray-900 dark:text-white">Productos</h2>
                        </div>
                        <div class="divide-y divide-gray-200 dark:divide-gray-700">
                            <div v-for="item in order.items" :key="item.id" class="p-4 flex items-center gap-4">
                                <div class="h-16 w-16 rounded-lg bg-gray-100 dark:bg-gray-700 overflow-hidden flex-shrink-0">
                                    <img v-if="item.image_url" :src="item.image_url" class="h-16 w-16 object-cover">
                                    <div v-else class="h-16 w-16 flex items-center justify-center text-gray-400">
                                        <svg class="w-8 h-8" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
                                        </svg>
                                    </div>
                                </div>
                                <div class="flex-1">
                                    <h3 class="font-medium text-gray-900 dark:text-white">{{ item.product_name }}</h3>
                                    <p class="text-sm text-gray-500">SKU: {{ item.product_sku }}</p>
                                </div>
                                <div class="text-right">
                                    <div class="text-sm text-gray-500">{{ item.quantity }} x {{ formatCurrency(item.price) }}</div>
                                    <div class="font-medium text-gray-900 dark:text-white">{{ formatCurrency(item.subtotal) }}</div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Shipping Address -->
                    <div v-if="order.shipping_address" class="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 p-6">
                        <h2 class="font-semibold text-gray-900 dark:text-white mb-4">Dirección de Envío</h2>
                        <div class="text-gray-600 dark:text-gray-400 space-y-1">
                            <p class="font-medium text-gray-900 dark:text-white">{{ order.shipping_address.first_name }} {{ order.shipping_address.last_name }}</p>
                            <p>{{ order.shipping_address.address_line1 }}</p>
                            <p v-if="order.shipping_address.address_line2">{{ order.shipping_address.address_line2 }}</p>
                            <p>{{ order.shipping_address.city }}, {{ order.shipping_address.state }} {{ order.shipping_address.postal_code }}</p>
                            <p v-if="order.shipping_address.phone">Tel: {{ order.shipping_address.phone }}</p>
                        </div>
                    </div>

                    <!-- Tracking -->
                    <div v-if="order.tracking_number" class="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 p-6">
                        <h2 class="font-semibold text-gray-900 dark:text-white mb-4">Información de Envío</h2>
                        <div class="space-y-2">
                            <p><span class="text-gray-500">Número de rastreo:</span> <span class="font-mono font-medium dark:text-white">{{ order.tracking_number }}</span></p>
                            <a v-if="order.tracking_url" :href="order.tracking_url" target="_blank" class="text-blue-600 hover:underline">Ver en la paquetería →</a>
                        </div>
                    </div>

                    <!-- Notes -->
                    <div v-if="order.notes || order.admin_notes" class="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 p-6">
                        <h2 class="font-semibold text-gray-900 dark:text-white mb-4">Notas</h2>
                        <div v-if="order.notes" class="mb-4">
                            <p class="text-sm text-gray-500 mb-1">Nota del cliente:</p>
                            <p class="text-gray-700 dark:text-gray-300">{{ order.notes }}</p>
                        </div>
                        <div v-if="order.admin_notes">
                            <p class="text-sm text-gray-500 mb-1">Notas internas:</p>
                            <p class="text-gray-700 dark:text-gray-300">{{ order.admin_notes }}</p>
                        </div>
                    </div>
                </div>

                <!-- Sidebar -->
                <div class="space-y-6">
                    <!-- Summary -->
                    <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 p-6">
                        <h2 class="font-semibold text-gray-900 dark:text-white mb-4">Resumen</h2>

                        <div class="space-y-3 text-sm">
                            <div class="flex justify-between">
                                <span class="text-gray-500">Subtotal</span>
                                <span class="dark:text-white">{{ formatCurrency(order.subtotal) }}</span>
                            </div>
                            <div v-if="order.discount > 0" class="flex justify-between text-green-600">
                                <span>Descuento</span>
                                <span>-{{ formatCurrency(order.discount) }}</span>
                            </div>
                            <div v-if="order.tax > 0" class="flex justify-between">
                                <span class="text-gray-500">Impuesto</span>
                                <span class="dark:text-white">{{ formatCurrency(order.tax) }}</span>
                            </div>
                            <div v-if="order.shipping > 0" class="flex justify-between">
                                <span class="text-gray-500">Envío</span>
                                <span class="dark:text-white">{{ formatCurrency(order.shipping) }}</span>
                            </div>
                            <div class="flex justify-between pt-3 border-t dark:border-gray-700 font-bold text-lg">
                                <span class="dark:text-white">Total</span>
                                <span class="text-green-600">{{ formatCurrency(order.total) }}</span>
                            </div>
                        </div>

                        <div v-if="order.coupon_code" class="mt-4 p-3 bg-green-50 dark:bg-green-900/20 rounded-lg">
                            <p class="text-sm text-green-700 dark:text-green-400">Cupón aplicado: <span class="font-mono font-bold">{{ order.coupon_code }}</span></p>
                        </div>
                    </div>

                    <!-- Status -->
                    <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 p-6">
                        <h2 class="font-semibold text-gray-900 dark:text-white mb-4">Estado</h2>

                        <div class="space-y-4">
                            <div class="flex items-center justify-between">
                                <span class="text-gray-500">Pedido</span>
                                <span :class="['px-3 py-1 text-sm rounded-full', statusColors[order.status]]">
                                    {{ statusLabels[order.status] }}
                                </span>
                            </div>
                            <div class="flex items-center justify-between">
                                <span class="text-gray-500">Pago</span>
                                <span :class="[
                                    'px-3 py-1 text-sm rounded-full',
                                    order.payment_status === 'paid'
                                        ? 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400'
                                        : 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400'
                                ]">
                                    {{ order.payment_status === 'paid' ? 'Pagado' : 'Pendiente' }}
                                </span>
                            </div>
                            <div v-if="order.payment_method" class="text-sm text-gray-500">
                                Método: {{ order.payment_method }}
                            </div>
                        </div>
                    </div>

                    <!-- Customer -->
                    <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 p-6">
                        <h2 class="font-semibold text-gray-900 dark:text-white mb-4">Cliente</h2>

                        <div class="flex items-center gap-3">
                            <div class="h-12 w-12 rounded-full bg-gray-200 dark:bg-gray-700 flex items-center justify-center text-gray-600 dark:text-gray-300 font-bold">
                                {{ order.user?.name?.charAt(0)?.toUpperCase() }}
                            </div>
                            <div>
                                <p class="font-medium text-gray-900 dark:text-white">{{ order.user?.name }}</p>
                                <p class="text-sm text-gray-500">{{ order.user?.email }}</p>
                            </div>
                        </div>
                    </div>

                    <!-- Timeline -->
                    <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 p-6">
                        <h2 class="font-semibold text-gray-900 dark:text-white mb-4">Línea de Tiempo</h2>

                        <div class="space-y-4 text-sm">
                            <div class="flex gap-3">
                                <div class="w-2 h-2 mt-1.5 rounded-full bg-gray-400"></div>
                                <div>
                                    <p class="text-gray-900 dark:text-white">Pedido creado</p>
                                    <p class="text-gray-500">{{ formatDate(order.created_at) }}</p>
                                </div>
                            </div>
                            <div v-if="order.paid_at" class="flex gap-3">
                                <div class="w-2 h-2 mt-1.5 rounded-full bg-green-500"></div>
                                <div>
                                    <p class="text-gray-900 dark:text-white">Pago recibido</p>
                                    <p class="text-gray-500">{{ formatDate(order.paid_at) }}</p>
                                </div>
                            </div>
                            <div v-if="order.shipped_at" class="flex gap-3">
                                <div class="w-2 h-2 mt-1.5 rounded-full bg-indigo-500"></div>
                                <div>
                                    <p class="text-gray-900 dark:text-white">Pedido enviado</p>
                                    <p class="text-gray-500">{{ formatDate(order.shipped_at) }}</p>
                                </div>
                            </div>
                            <div v-if="order.delivered_at" class="flex gap-3">
                                <div class="w-2 h-2 mt-1.5 rounded-full bg-green-500"></div>
                                <div>
                                    <p class="text-gray-900 dark:text-white">Pedido entregado</p>
                                    <p class="text-gray-500">{{ formatDate(order.delivered_at) }}</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Status Update Modal -->
        <Teleport to="body">
            <div v-if="showStatusModal" class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50">
                <div class="bg-white dark:bg-gray-800 rounded-2xl shadow-xl w-full max-w-md">
                    <div class="p-6 border-b dark:border-gray-700">
                        <h2 class="text-lg font-semibold text-gray-900 dark:text-white">Actualizar Estado</h2>
                    </div>

                    <form @submit.prevent="updateStatus" class="p-6 space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Estado</label>
                            <select v-model="form.status" class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white">
                                <option value="pending">Pendiente</option>
                                <option value="processing">Procesando</option>
                                <option value="shipped">Enviado</option>
                                <option value="delivered">Entregado</option>
                                <option value="cancelled">Cancelado</option>
                                <option value="refunded">Reembolsado</option>
                            </select>
                        </div>

                        <div v-if="form.status === 'shipped'">
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Número de rastreo</label>
                            <input v-model="form.tracking_number" type="text" class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white">
                        </div>

                        <div v-if="form.status === 'shipped'">
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">URL de rastreo</label>
                            <input v-model="form.tracking_url" type="url" class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white" placeholder="https://...">
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Notas internas</label>
                            <textarea v-model="form.admin_notes" rows="3" class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white"></textarea>
                        </div>
                    </form>

                    <div class="p-6 border-t dark:border-gray-700 flex justify-end gap-3">
                        <button @click="showStatusModal = false" class="px-4 py-2 text-gray-600 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg">Cancelar</button>
                        <button @click="updateStatus" :disabled="form.processing" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50">
                            {{ form.processing ? 'Guardando...' : 'Actualizar' }}
                        </button>
                    </div>
                </div>
            </div>
        </Teleport>
    </AdminLayout>
</template>
