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

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

const showCancelModal = ref(false);
const cancelForm = useForm({
    reason: '',
});

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

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

const getStatusClass = (status) => {
    return {
        'paid': 'bg-green-100 text-green-800 dark:bg-green-900/50 dark:text-green-300',
        'pending': 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/50 dark:text-yellow-300',
        'cancelled': 'bg-red-100 text-red-800 dark:bg-red-900/50 dark:text-red-300',
    }[status] || 'bg-gray-100 text-gray-800';
};

const getStatusLabel = (status) => {
    return {
        'paid': 'Pagada',
        'pending': 'Pendiente',
        'cancelled': 'Cancelada',
    }[status] || status;
};

const getPaymentMethodLabel = (method) => {
    return {
        'stripe': '💳 Stripe (Tarjeta)',
        'paypal': '🅿️ PayPal',
        'bank_transfer': '🏦 Transferencia Bancaria',
        'cash': '💵 Efectivo',
        'wallet': '👛 Billetera',
        'other': '📝 Otro',
    }[method] || method || 'No especificado';
};

const submitCancel = () => {
    cancelForm.post(route('admin.invoices.cancel', props.invoice.id), {
        onSuccess: () => {
            showCancelModal.value = false;
        },
    });
};
</script>

<template>
    <Head :title="`Factura ${invoice.invoice_number}`" />

    <AdminLayout>
        <template #header>
            <div class="flex justify-between items-center">
                <div>
                    <Link :href="route('admin.invoices.index')" class="text-blue-600 hover:underline text-sm mb-1 inline-block">
                        ← Volver a Facturas
                    </Link>
                    <h2 class="text-xl font-semibold text-gray-800 dark:text-white">Factura {{ invoice.invoice_number }}</h2>
                </div>
                <div class="flex gap-2">
                    <a :href="route('admin.invoices.download', invoice.id)"
                       class="bg-blue-600 text-white px-4 py-2 rounded-lg text-sm hover:bg-blue-700 transition flex items-center gap-2">
                        📥 Descargar PDF
                    </a>
                    <button v-if="invoice.status === 'pending'"
                            @click="showCancelModal = true"
                            class="bg-red-100 text-red-700 px-4 py-2 rounded-lg text-sm hover:bg-red-200 transition">
                        ❌ Cancelar
                    </button>
                </div>
            </div>
        </template>

        <div class="py-6">
            <div class="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 space-y-6">

                <!-- Status Banner -->
                <div :class="['rounded-xl p-4 flex items-center justify-between',
                    invoice.status === 'paid' ? 'bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800' :
                    invoice.status === 'pending' ? 'bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800' :
                    'bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800']">
                    <div class="flex items-center gap-3">
                        <span class="text-3xl">
                            {{ invoice.status === 'paid' ? '✅' : invoice.status === 'pending' ? '⏳' : '❌' }}
                        </span>
                        <div>
                            <span :class="['font-bold text-lg',
                                invoice.status === 'paid' ? 'text-green-800 dark:text-green-300' :
                                invoice.status === 'pending' ? 'text-yellow-800 dark:text-yellow-300' :
                                'text-red-800 dark:text-red-300']">
                                {{ getStatusLabel(invoice.status) }}
                            </span>
                            <p v-if="invoice.paid_at" class="text-sm text-green-600 dark:text-green-400">
                                Pagada el {{ formatDate(invoice.paid_at) }}
                            </p>
                        </div>
                    </div>
                    <div class="text-right">
                        <div class="text-3xl font-bold text-gray-900 dark:text-white">{{ formatCurrency(invoice.total) }}</div>
                        <div v-if="invoice.payment_method" class="text-sm text-gray-600 dark:text-gray-400">
                            {{ getPaymentMethodLabel(invoice.payment_method) }}
                        </div>
                    </div>
                </div>

                <div class="grid md:grid-cols-2 gap-6">
                    <!-- Invoice Details -->
                    <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm p-6">
                        <h3 class="text-lg font-bold text-gray-900 dark:text-white mb-4">📄 Detalles de Factura</h3>
                        <dl class="space-y-3">
                            <div class="flex justify-between">
                                <dt class="text-sm text-gray-500 dark:text-gray-400">Número</dt>
                                <dd class="text-sm font-mono font-semibold text-gray-900 dark:text-white">{{ invoice.invoice_number }}</dd>
                            </div>
                            <div class="flex justify-between">
                                <dt class="text-sm text-gray-500 dark:text-gray-400">Fecha de Emisión</dt>
                                <dd class="text-sm text-gray-900 dark:text-white">{{ formatDate(invoice.created_at) }}</dd>
                            </div>
                            <div class="flex justify-between" v-if="invoice.paid_at">
                                <dt class="text-sm text-gray-500 dark:text-gray-400">Fecha de Pago</dt>
                                <dd class="text-sm text-green-600 dark:text-green-400 font-medium">{{ formatDate(invoice.paid_at) }}</dd>
                            </div>
                            <div class="flex justify-between" v-if="invoice.transaction_id">
                                <dt class="text-sm text-gray-500 dark:text-gray-400">ID Transacción</dt>
                                <dd class="text-sm font-mono text-gray-900 dark:text-white">{{ invoice.transaction_id }}</dd>
                            </div>
                            <div class="border-t dark:border-gray-700 pt-3 mt-3">
                                <div class="flex justify-between">
                                    <dt class="text-sm text-gray-500 dark:text-gray-400">Subtotal</dt>
                                    <dd class="text-sm text-gray-900 dark:text-white">{{ formatCurrency(invoice.subtotal) }}</dd>
                                </div>
                                <div class="flex justify-between">
                                    <dt class="text-sm text-gray-500 dark:text-gray-400">Impuesto</dt>
                                    <dd class="text-sm text-gray-900 dark:text-white">{{ formatCurrency(invoice.tax) }}</dd>
                                </div>
                                <div class="flex justify-between font-bold mt-2 pt-2 border-t dark:border-gray-700">
                                    <dt class="text-gray-900 dark:text-white">Total</dt>
                                    <dd class="text-blue-600 dark:text-blue-400 text-lg">{{ formatCurrency(invoice.total) }}</dd>
                                </div>
                            </div>
                        </dl>
                    </div>

                    <!-- Coach Details -->
                    <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm p-6">
                        <h3 class="text-lg font-bold text-gray-900 dark:text-white mb-4">👤 Datos del Coach</h3>
                        <div class="flex items-center gap-4 mb-4">
                            <div class="w-16 h-16 rounded-full bg-blue-100 dark:bg-blue-900/50 flex items-center justify-center text-blue-600 dark:text-blue-400 font-bold text-2xl">
                                {{ invoice.user?.name?.charAt(0) || '?' }}
                            </div>
                            <div>
                                <div class="text-lg font-semibold text-gray-900 dark:text-white">{{ invoice.user?.name || 'N/A' }}</div>
                                <div class="text-sm text-gray-500 dark:text-gray-400">{{ invoice.user?.email || 'N/A' }}</div>
                            </div>
                        </div>
                        <Link :href="route('admin.users.show', invoice.user?.id)" class="text-blue-600 hover:underline text-sm">
                            Ver perfil completo →
                        </Link>
                    </div>
                </div>

                <!-- Subscription/Plan Details -->
                <div v-if="invoice.subscription" class="bg-white dark:bg-gray-800 rounded-xl shadow-sm p-6">
                    <h3 class="text-lg font-bold text-gray-900 dark:text-white mb-4">📦 Información del Plan</h3>
                    <div class="grid md:grid-cols-3 gap-4">
                        <div>
                            <div class="text-sm text-gray-500 dark:text-gray-400">Plan</div>
                            <div class="text-lg font-semibold text-gray-900 dark:text-white">{{ invoice.subscription.plan?.name || 'N/A' }}</div>
                        </div>
                        <div>
                            <div class="text-sm text-gray-500 dark:text-gray-400">Período</div>
                            <div class="text-sm text-gray-900 dark:text-white">
                                {{ formatDate(invoice.subscription.start_date) }} - {{ formatDate(invoice.subscription.end_date) }}
                            </div>
                        </div>
                        <div>
                            <div class="text-sm text-gray-500 dark:text-gray-400">Estado Suscripción</div>
                            <span :class="['px-2 py-1 rounded-full text-xs font-semibold',
                                invoice.subscription.status === 'active' ? 'bg-green-100 text-green-800 dark:bg-green-900/50 dark:text-green-300' :
                                'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/50 dark:text-yellow-300']">
                                {{ invoice.subscription.status === 'active' ? 'Activa' : invoice.subscription.status }}
                            </span>
                        </div>
                    </div>
                </div>

                <!-- Notes -->
                <div v-if="invoice.notes" class="bg-white dark:bg-gray-800 rounded-xl shadow-sm p-6">
                    <h3 class="text-lg font-bold text-gray-900 dark:text-white mb-2">📝 Notas</h3>
                    <p class="text-gray-600 dark:text-gray-400">{{ invoice.notes }}</p>
                </div>

                <!-- Receipt / Comprobante -->
                <div v-if="invoice.receipt_path || invoice.selected_bank" class="bg-white dark:bg-gray-800 rounded-xl shadow-sm p-6">
                    <h3 class="text-lg font-bold text-gray-900 dark:text-white mb-4">🧾 Comprobante de Pago</h3>

                    <!-- Selected Bank -->
                    <div v-if="invoice.selected_bank" class="flex items-center gap-3 p-3 mb-4 bg-blue-50 dark:bg-blue-900/20 rounded-lg border border-blue-200 dark:border-blue-800">
                        <span class="text-xl">🏦</span>
                        <div>
                            <p class="text-sm text-blue-700 dark:text-blue-300 font-medium">Banco seleccionado por el coach:</p>
                            <p class="font-semibold text-blue-900 dark:text-blue-100">{{ invoice.selected_bank.bank_name }}</p>
                        </div>
                    </div>

                    <!-- Receipt Image -->
                    <div v-if="invoice.receipt_path">
                        <p class="text-sm text-gray-500 dark:text-gray-400 mb-2">Comprobante adjuntado:</p>
                        <div class="bg-gray-50 dark:bg-gray-900 rounded-xl overflow-hidden border border-gray-200 dark:border-gray-700">
                            <img v-if="!invoice.receipt_path.endsWith('.pdf')"
                                 :src="'/storage/' + invoice.receipt_path"
                                 alt="Comprobante de pago"
                                 class="w-full h-auto max-h-[400px] object-contain mx-auto" />
                            <div v-else class="flex items-center justify-center p-8">
                                <a :href="'/storage/' + invoice.receipt_path" target="_blank"
                                   class="inline-flex items-center gap-2 px-4 py-2 bg-red-100 text-red-700 rounded-lg hover:bg-red-200 transition">
                                    📄 Ver PDF del comprobante
                                </a>
                            </div>
                        </div>
                        <a :href="'/storage/' + invoice.receipt_path" target="_blank" download
                           class="inline-flex items-center gap-2 mt-3 text-sm text-blue-600 hover:text-blue-700 dark:text-blue-400 dark:hover:text-blue-300">
                            📥 Descargar comprobante
                        </a>
                    </div>

                    <div v-else class="text-center py-4">
                        <p class="text-sm text-gray-400">El coach no adjuntó comprobante</p>
                    </div>
                </div>

                <!-- Items (if any) -->
                <div v-if="invoice.items && invoice.items.length" class="bg-white dark:bg-gray-800 rounded-xl shadow-sm p-6">
                    <h3 class="text-lg font-bold text-gray-900 dark:text-white mb-4">📋 Detalle de Ítems</h3>
                    <table class="w-full">
                        <thead class="bg-gray-50 dark:bg-gray-700">
                            <tr>
                                <th class="px-4 py-2 text-left text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase">Concepto</th>
                                <th class="px-4 py-2 text-right text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase">Cantidad</th>
                                <th class="px-4 py-2 text-right text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase">Precio</th>
                                <th class="px-4 py-2 text-right text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase">Total</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-100 dark:divide-gray-700">
                            <tr v-for="item in invoice.items" :key="item.name">
                                <td class="px-4 py-3 text-sm text-gray-900 dark:text-white">{{ item.name }}</td>
                                <td class="px-4 py-3 text-sm text-right text-gray-700 dark:text-gray-300">{{ item.quantity || 1 }}</td>
                                <td class="px-4 py-3 text-sm text-right text-gray-700 dark:text-gray-300">{{ formatCurrency(item.price) }}</td>
                                <td class="px-4 py-3 text-sm text-right font-semibold text-gray-900 dark:text-white">{{ formatCurrency(item.total || item.price) }}</td>
                            </tr>
                        </tbody>
                    </table>
                </div>

            </div>
        </div>

        <!-- Cancel Modal -->
        <div v-if="showCancelModal" 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-2xl max-w-md w-full p-6">
                <h3 class="text-xl font-bold text-gray-900 dark:text-white mb-2">❌ Cancelar Factura</h3>
                <p class="text-sm text-gray-500 dark:text-gray-400 mb-6">
                    ¿Estás seguro de cancelar la factura <strong>{{ invoice.invoice_number }}</strong>? Esta acción no se puede deshacer.
                </p>

                <form @submit.prevent="submitCancel" class="space-y-4">
                    <div>
                        <label class="block text-sm font-semibold text-gray-700 dark:text-gray-300 mb-1">Razón de Cancelación</label>
                        <textarea v-model="cancelForm.reason" rows="3" class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white" placeholder="Motivo de la cancelación..."></textarea>
                    </div>

                    <div class="flex justify-end gap-3 pt-4">
                        <button type="button" @click="showCancelModal = false" class="px-4 py-2 text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg">
                            No, Volver
                        </button>
                        <button type="submit" :disabled="cancelForm.processing" class="px-6 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 disabled:opacity-50">
                            {{ cancelForm.processing ? 'Cancelando...' : 'Sí, Cancelar' }}
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </AdminLayout>
</template>
