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

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

const search = ref(props.filters.search || '');
const status = ref(props.filters.status || '');

let timeout = null;
watch([search, status], () => {
    clearTimeout(timeout);
    timeout = setTimeout(() => {
        router.get(route('admin.store.coupons.index'), {
            search: search.value,
            status: status.value,
        }, { preserveState: true, replace: true });
    }, 300);
});

const showModal = ref(false);
const editingCoupon = ref(null);

const form = useForm({
    code: '',
    name: '',
    description: '',
    type: 'percentage',
    value: 10,
    min_order: null,
    max_discount: null,
    usage_limit: null,
    per_user_limit: null,
    starts_at: null,
    expires_at: null,
    is_active: true,
});

const openModal = (coupon = null) => {
    editingCoupon.value = coupon;
    if (coupon) {
        Object.keys(form.data()).forEach(key => {
            if (coupon[key] !== undefined) {
                form[key] = coupon[key];
            }
        });
    } else {
        form.reset();
        form.code = '';
    }
    showModal.value = true;
};

const closeModal = () => {
    showModal.value = false;
    editingCoupon.value = null;
    form.reset();
};

const submit = () => {
    if (editingCoupon.value) {
        form.put(route('admin.store.coupons.update', editingCoupon.value.id), {
            onSuccess: closeModal,
        });
    } else {
        form.post(route('admin.store.coupons.store'), {
            onSuccess: closeModal,
        });
    }
};

const deleteCoupon = (coupon) => {
    if (confirm(`¿Eliminar el cupón "${coupon.code}"?`)) {
        router.delete(route('admin.store.coupons.destroy', coupon.id));
    }
};

const toggleCoupon = (coupon) => {
    router.post(route('admin.store.coupons.toggle', coupon.id));
};

const formatCurrency = (value) => {
    return new Intl.NumberFormat('es-DO', { style: 'currency', currency: 'USD' }).format(value);
};
</script>

<template>
    <Head title="Cupones" />
    
    <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>
                    <h1 class="text-2xl font-bold text-gray-900 dark:text-white">Cupones</h1>
                    <p class="text-gray-500 dark:text-gray-400">Gestiona códigos de descuento para la tienda</p>
                </div>
                <button 
                    @click="openModal()"
                    class="inline-flex items-center px-4 py-2 bg-gradient-to-r from-blue-600 to-blue-700 text-white font-medium rounded-lg hover:from-blue-700 hover:to-blue-800 transition-all"
                >
                    <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
                    </svg>
                    Nuevo Cupón
                </button>
            </div>

            <!-- Filters -->
            <div class="mb-6 bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 p-4">
                <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <input v-model="search" type="text" placeholder="Buscar por código o nombre..." class="rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white">
                    <select v-model="status" class="rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white">
                        <option value="">Todos</option>
                        <option value="active">Activos</option>
                        <option value="expired">Expirados/Inactivos</option>
                    </select>
                </div>
            </div>

            <!-- Table -->
            <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 overflow-hidden">
                <div class="overflow-x-auto">
                    <table class="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
                        <thead class="bg-gray-50 dark:bg-gray-700">
                            <tr>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase">Código</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase">Descuento</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase">Uso</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase">Validez</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase">Estado</th>
                                <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-300 uppercase">Acciones</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-200 dark:divide-gray-700">
                            <tr v-for="coupon in (coupons?.data || [])" :key="coupon.id" class="hover:bg-gray-50 dark:hover:bg-gray-700/50">
                                <td class="px-6 py-4">
                                    <div class="font-mono font-bold text-gray-900 dark:text-white">{{ coupon.code }}</div>
                                    <div class="text-sm text-gray-500">{{ coupon.name }}</div>
                                </td>
                                <td class="px-6 py-4">
                                    <span class="text-lg font-bold text-green-600 dark:text-green-400">
                                        {{ coupon.type === 'percentage' ? coupon.value + '%' : formatCurrency(coupon.value) }}
                                    </span>
                                    <div v-if="coupon.min_order" class="text-xs text-gray-500">Mín: {{ formatCurrency(coupon.min_order) }}</div>
                                </td>
                                <td class="px-6 py-4 text-sm">
                                    <span class="font-medium dark:text-white">{{ coupon.usage_count }}</span>
                                    <span class="text-gray-500">{{ coupon.usage_limit ? '/ ' + coupon.usage_limit : '/ ∞' }}</span>
                                </td>
                                <td class="px-6 py-4 text-sm text-gray-500 dark:text-gray-400">
                                    <div v-if="coupon.starts_at">Desde: {{ new Date(coupon.starts_at).toLocaleDateString() }}</div>
                                    <div v-if="coupon.expires_at">Hasta: {{ new Date(coupon.expires_at).toLocaleDateString() }}</div>
                                    <span v-if="!coupon.starts_at && !coupon.expires_at">Sin límite</span>
                                </td>
                                <td class="px-6 py-4">
                                    <button @click="toggleCoupon(coupon)" :class="[
                                        'px-2 py-1 text-xs rounded-full cursor-pointer transition',
                                        coupon.is_active 
                                            ? 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400' 
                                            : 'bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-400'
                                    ]">
                                        {{ coupon.is_active ? 'Activo' : 'Inactivo' }}
                                    </button>
                                </td>
                                <td class="px-6 py-4 text-right">
                                    <div class="flex items-center justify-end gap-2">
                                        <button @click="openModal(coupon)" class="p-1.5 rounded-lg hover:bg-blue-50 dark:hover:bg-blue-900/20 text-blue-600 transition">
                                            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                                            </svg>
                                        </button>
                                        <button @click="deleteCoupon(coupon)" class="p-1.5 rounded-lg hover:bg-red-50 dark:hover:bg-red-900/20 text-red-600 transition">
                                            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                                            </svg>
                                        </button>
                                    </div>
                                </td>
                            </tr>
                            <tr v-if="!coupons?.data?.length">
                                <td colspan="6" class="px-6 py-12 text-center text-gray-500">
                                    <svg class="mx-auto h-12 w-12 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 5v2m0 4v2m0 4v2M5 5a2 2 0 00-2 2v3a2 2 0 110 4v3a2 2 0 002 2h14a2 2 0 002-2v-3a2 2 0 110-4V7a2 2 0 00-2-2H5z" />
                                    </svg>
                                    <p class="mt-2">No hay cupones</p>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Modal -->
        <Teleport to="body">
            <div v-if="showModal" 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-lg max-h-[90vh] overflow-y-auto">
                    <div class="p-6 border-b dark:border-gray-700 sticky top-0 bg-white dark:bg-gray-800">
                        <h2 class="text-lg font-semibold text-gray-900 dark:text-white">
                            {{ editingCoupon ? 'Editar Cupón' : 'Nuevo Cupón' }}
                        </h2>
                    </div>

                    <form @submit.prevent="submit" class="p-6 space-y-4">
                        <div class="grid grid-cols-2 gap-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Código</label>
                                <input v-model="form.code" type="text" class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white font-mono uppercase" placeholder="Auto-generado">
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Nombre *</label>
                                <input v-model="form.name" type="text" class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white" required>
                            </div>
                        </div>

                        <div class="grid grid-cols-2 gap-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Tipo</label>
                                <select v-model="form.type" class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white">
                                    <option value="percentage">Porcentaje (%)</option>
                                    <option value="fixed">Monto fijo ($)</option>
                                </select>
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Valor *</label>
                                <div class="relative">
                                    <span class="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500">{{ form.type === 'percentage' ? '%' : '$' }}</span>
                                    <input v-model="form.value" type="number" step="0.01" min="0" class="w-full pl-8 rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white" required>
                                </div>
                            </div>
                        </div>

                        <div class="grid grid-cols-2 gap-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Pedido mínimo</label>
                                <input v-model="form.min_order" type="number" step="0.01" min="0" class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white" placeholder="Sin mínimo">
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Descuento máximo</label>
                                <input v-model="form.max_discount" type="number" step="0.01" min="0" class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white" placeholder="Sin límite">
                            </div>
                        </div>

                        <div class="grid grid-cols-2 gap-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Límite de uso</label>
                                <input v-model="form.usage_limit" type="number" min="1" class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white" placeholder="Ilimitado">
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Por usuario</label>
                                <input v-model="form.per_user_limit" type="number" min="1" class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white" placeholder="Ilimitado">
                            </div>
                        </div>

                        <div class="grid grid-cols-2 gap-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Fecha inicio</label>
                                <input v-model="form.starts_at" type="date" class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white">
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Fecha fin</label>
                                <input v-model="form.expires_at" type="date" class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white">
                            </div>
                        </div>

                        <label class="flex items-center gap-2">
                            <input v-model="form.is_active" type="checkbox" class="rounded border-gray-300 text-blue-600">
                            <span class="text-sm text-gray-700 dark:text-gray-300">Cupón activo</span>
                        </label>
                    </form>

                    <div class="p-6 border-t dark:border-gray-700 flex justify-end gap-3 sticky bottom-0 bg-white dark:bg-gray-800">
                        <button @click="closeModal" class="px-4 py-2 text-gray-600 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg">Cancelar</button>
                        <button @click="submit" :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...' : (editingCoupon ? 'Actualizar' : 'Crear') }}
                        </button>
                    </div>
                </div>
            </div>
        </Teleport>
    </AdminLayout>
</template>
