<script setup>
import { ref, onMounted, watch } from 'vue';
import { useRoute } from 'vue-router';
import axios from 'axios';
import { apiURL } from '@Services/Api';
import GoogleIcon     from '@Shared/GoogleIcon.vue';


/** Ruta actual (para leer :qr_token) */
const route    = useRoute();
const qrToken  = route.params.qr_token;

/** Estado general */
const loading         = ref(true);
const notFound        = ref(false);
const paymentData     = ref(null);
const invoiceRequest  = ref(null);
const hasInvoiceReq   = ref(false);
const submitted       = ref(false);
const submitting      = ref(false);
const serverErrors    = ref({});

/** Catálogos SAT */
const fiscalRegimes = ref([]);
const cfdiUses      = ref([]);
const loadingCfdi   = ref(false);

/** Formulario ciudadano */
const form = ref({
    rfc:                '',
    email:              '',
    phone:              '',
    name:               '',
    business_name:      '',
    fiscal_postal_code: '',
    address:            '',
    fiscal_regimen_id:  null,
    cfdi_use_id:        null,
    selectedRegime:     null,
    selectedCfdiUse:    null,
});

/** HTTP sin autenticación */
const publicGet  = (path, params = {}) =>
    axios.get(apiURL(path), { params, headers: { Accept: 'application/json' } });

const publicPost = (path, data = {}) =>
    axios.post(apiURL(path), data, { headers: { 'Content-Type': 'application/json', Accept: 'application/json' } });

/** Al cargar — obtener datos del pago */
onMounted(async () => {
    try {
        const { data } = await publicGet(`invoice-request/payment/${qrToken}`);
        const res = data?.data ?? data;
        paymentData.value    = res.model;
        hasInvoiceReq.value  = res.has_invoice_request;
        invoiceRequest.value = res.model?.invoice_request ?? null;

        // Prellenar RFC si el pago tiene uno registrado
        if (res.model?.model?.rfc) {
            form.value.rfc = res.model.model.rfc;
        }
    } catch (err) {
        if (err.response?.status === 404) {
            notFound.value = true;
        }
    } finally {
        loading.value = false;
    }

    // Cargar regímenes fiscales en paralelo
    loadFiscalRegimes();
});

const loadFiscalRegimes = async () => {
    try {
        const { data } = await publicGet('sat/fiscal-regimes');
        const res = data?.data ?? data;
        fiscalRegimes.value = res.models?.data ?? res.models ?? [];
    } catch {}
};

/** Al cambiar régimen — obtener usos de CFDI compatibles */
const onRegimeChange = async (regime) => {
    form.value.fiscal_regimen_id = regime?.id ?? null;
    form.value.cfdi_use_id       = null;
    form.value.selectedCfdiUse   = null;
    cfdiUses.value               = [];

    if (!regime?.code) return;

    loadingCfdi.value = true;
    try {
        const { data } = await publicGet('sat/cfdi-uses', { fiscal_regime: regime.code });
        const res = data?.data ?? data;
        cfdiUses.value = res.models?.data ?? res.models ?? [];
    } catch {
        cfdiUses.value = [];
    } finally {
        loadingCfdi.value = false;
    }
};

const onCfdiChange = (use) => {
    form.value.cfdi_use_id = use?.id ?? null;
};

/** Validaciones básicas del cliente */
const rfcRegex = /^[A-ZÑ&]{3,4}\d{6}[A-Z0-9]{3}$/i;

const validate = () => {
    const errors = {};
    const rfc = form.value.rfc.trim().toUpperCase();
    if (!rfc) {
        errors.rfc = 'El RFC es obligatorio.';
    } else if (!rfcRegex.test(rfc)) {
        errors.rfc = 'El RFC no tiene un formato válido (ej. XAXX010101000).';
    }
    if (!form.value.email.trim()) errors.email = 'El correo electrónico es obligatorio.';
    if (!form.value.fiscal_regimen_id) errors.fiscal_regimen_id = 'Selecciona un régimen fiscal.';
    if (!form.value.cfdi_use_id)       errors.cfdi_use_id       = 'Selecciona el uso del CFDI.';
    if (!form.value.fiscal_postal_code.trim()) {
        errors.fiscal_postal_code = 'El código postal fiscal es obligatorio.';
    } else if (!/^\d{5}$/.test(form.value.fiscal_postal_code.trim())) {
        errors.fiscal_postal_code = 'El código postal debe tener exactamente 5 dígitos.';
    }
    return errors;
};

/** Enviar solicitud */
const submitRequest = async () => {
    serverErrors.value = {};
    const clientErrors = validate();
    if (Object.keys(clientErrors).length) {
        serverErrors.value = clientErrors;
        return;
    }

    submitting.value = true;
    try {
        const payload = {
            qr_token:           qrToken,
            rfc:                form.value.rfc.trim().toUpperCase(),
            email:              form.value.email.trim(),
            fiscal_regimen_id:  form.value.fiscal_regimen_id,
            cfdi_use_id:        form.value.cfdi_use_id,
            fiscal_postal_code: form.value.fiscal_postal_code.trim(),
        };
        if (form.value.phone.trim())         payload.phone         = form.value.phone.trim();
        if (form.value.name.trim())          payload.name          = form.value.name.trim();
        if (form.value.business_name.trim()) payload.business_name = form.value.business_name.trim();
        if (form.value.address.trim())       payload.address       = form.value.address.trim();

        await publicPost('invoice-request', payload);
        submitted.value = true;
    } catch (err) {
        const status = err.response?.status;
        if (status === 422) {
            serverErrors.value = err.response.data?.errors ?? {};
        } else if (status === 409) {
            hasInvoiceReq.value  = true;
            invoiceRequest.value = { status: 'pending' };
        } else if (status === 404) {
            notFound.value = true;
        }
    } finally {
        submitting.value = false;
    }
};

const formatAmount = (a) =>
    a ? new Intl.NumberFormat('es-MX', { style: 'currency', currency: 'MXN' }).format(a) : '—';

const formatDate = (iso) =>
    iso ? new Date(iso).toLocaleDateString('es-MX', { year: 'numeric', month: 'long', day: 'numeric' }) : '—';
</script>

<template>
    <div class="min-h-screen bg-gray-100 flex flex-col">

        <!-- Encabezado -->
        <header class="bg-[#621134] text-white py-4 px-6 shadow">
            <div class="max-w-2xl mx-auto flex items-center gap-3">
                <GoogleIcon
                    class="text-3xl text-white"
                    name="receipt_long"
                />
                <div>
                    <p class="text-xs font-light opacity-80">H. Ayuntamiento de Comalcalco</p>
                    <h1 class="text-lg font-bold leading-tight">Solicitud de Factura Electrónica</h1>
                </div>
            </div>
        </header>

        <!-- Contenido principal -->
        <main class="flex-1 py-8 px-4">
            <div class="max-w-2xl mx-auto space-y-5">

                <!-- Cargando -->
                <div v-if="loading" class="bg-white rounded-xl shadow p-10 flex justify-center">
                    <div class="animate-spin rounded-full h-10 w-10 border-4 border-[#621134] border-t-transparent"></div>
                </div>

                <!-- QR inválido / no encontrado -->
                <div v-else-if="notFound" class="bg-white rounded-xl shadow p-8 text-center space-y-3">
                    <span class="material-symbols-outlined text-5xl text-red-400">qr_code_scanner</span>
                    <h2 class="text-lg font-bold text-gray-700">Código QR no válido</h2>
                    <p class="text-gray-500 text-sm">
                        El código QR no es válido o ya expiró. Si crees que es un error, comunícate con el
                        departamento de Tránsito Municipal.
                    </p>
                </div>

                <!-- Solicitud enviada exitosamente -->
                <div v-else-if="submitted" class="bg-white rounded-xl shadow p-8 text-center space-y-3">
                    <GoogleIcon
                        class="text-5xl text-green-500"
                        name="check_circle"
                    />
                    <h2 class="text-lg font-bold text-gray-700">¡Solicitud enviada!</h2>
                    <p class="text-gray-500 text-sm">
                        Tu solicitud de factura fue recibida correctamente. Te notificaremos cuando esté lista.
                    </p>
                </div>

                <!-- Estado de solicitud existente -->
                <template v-else-if="hasInvoiceReq && invoiceRequest">

                    <!-- Datos del pago -->
                    <div v-if="paymentData" class="bg-white rounded-xl shadow p-5">
                        <h2 class="text-sm font-semibold text-gray-500 uppercase tracking-wider mb-3">
                            Pago de referencia
                        </h2>
                        <div class="grid grid-cols-2 gap-2 text-sm">
                            <div><span class="text-gray-500">Titular:</span> <span class="font-medium">{{ paymentData.model?.name }}</span></div>
                            <div><span class="text-gray-500">Placa:</span> <span class="font-mono">{{ paymentData.model?.plate }}</span></div>
                            <div><span class="text-gray-500">Monto:</span> <span class="font-semibold text-green-700">{{ formatAmount(paymentData.total_amount) }}</span></div>
                            <div><span class="text-gray-500">Pagado el:</span> {{ formatDate(paymentData.paid_at) }}</div>
                        </div>
                    </div>

                    <!-- Mensaje de estado -->
                    <div class="bg-white rounded-xl shadow p-6 text-center space-y-2">
                        <template v-if="invoiceRequest.status === 'pending'">
                            <GoogleIcon
                                class="text-4xl text-yellow-500"
                                name="hourglass_empty"
                            />
                            <h2 class="text-base font-bold text-gray-700">Solicitud en espera</h2>
                            <p class="text-gray-500 text-sm">
                                Tu solicitud fue recibida y está en espera de procesarse.
                            </p>
                        </template>
                        <template v-else-if="invoiceRequest.status === 'processing'">
                            <GoogleIcon
                                class="text-4xl text-blue-500"
                                name="sync"
                            />
                            <h2 class="text-base font-bold text-gray-700">En proceso</h2>
                            <p class="text-gray-500 text-sm">
                                Tu factura está siendo generada, pronto te notificaremos.
                            </p>
                        </template>
                        <template v-else-if="invoiceRequest.status === 'completed'">
                            <GoogleIcon
                                class="text-4xl text-green-500"
                                name="task_alt"
                            />
                            <h2 class="text-base font-bold text-gray-700">Factura enviada</h2>
                            <p class="text-gray-500 text-sm">
                                Tu factura electrónica fue generada y enviada a tu WhatsApp. Revisa tus mensajes.
                            </p>
                        </template>
                        <template v-else-if="invoiceRequest.status === 'rejected'">
                            <GoogleIcon
                                class="text-4xl text-red-400"
                                name="cancel"
                            />
                            <h2 class="text-base font-bold text-gray-700">Solicitud no procesada</h2>
                            <p class="text-gray-500 text-sm">
                                Tu solicitud no pudo procesarse. Comunícate con el departamento de Tránsito Municipal.
                            </p>
                        </template>
                    </div>
                </template>

                <!-- Formulario ciudadano -->
                <template v-else-if="paymentData">

                    <!-- Datos del pago -->
                    <div class="bg-white rounded-xl shadow p-5">
                        <h2 class="text-sm font-semibold text-gray-500 uppercase tracking-wider mb-3">
                            Pago de referencia
                        </h2>
                        <div class="grid grid-cols-2 gap-2 text-sm">
                            <div><span class="text-gray-500">Titular:</span> <span class="font-medium">{{ paymentData.model?.name }}</span></div>
                            <div><span class="text-gray-500">Placa:</span> <span class="font-mono">{{ paymentData.model?.plate }}</span></div>
                            <div><span class="text-gray-500">Monto:</span> <span class="font-semibold text-green-700">{{ formatAmount(paymentData.total_amount) }}</span></div>
                            <div><span class="text-gray-500">Pagado el:</span> {{ formatDate(paymentData.paid_at) }}</div>
                        </div>

                        <!-- Conceptos -->
                        <div v-if="paymentData.model?.charge_concepts?.length" class="mt-3 pt-3 border-t">
                            <p class="text-xs text-gray-500 mb-1">Conceptos cobrados:</p>
                            <div
                                v-for="cc in paymentData.model.charge_concepts"
                                :key="cc.id"
                                class="flex justify-between text-xs text-gray-700 py-0.5"
                            >
                                <span>{{ cc.name }} <span class="text-gray-400">({{ cc.article }})</span></span>
                                <span class="font-medium">{{ formatAmount(cc.pivot?.override_amount) }}</span>
                            </div>
                        </div>
                    </div>

                    <!-- Formulario -->
                    <div class="bg-white rounded-xl shadow p-6">
                        <h2 class="text-base font-bold text-gray-700 mb-4">Datos para tu factura</h2>

                        <form class="space-y-4" @submit.prevent="submitRequest">

                            <!-- RFC -->
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">
                                    RFC <span class="text-red-500">*</span>
                                </label>
                                <input
                                    v-model="form.rfc"
                                    type="text"
                                    maxlength="13"
                                    placeholder="Ej. XAXX010101000"
                                    class="w-full border rounded-lg px-3 py-2 text-sm font-mono uppercase focus:outline-none focus:ring-2 focus:ring-[#621134]/40"
                                    :class="serverErrors.rfc ? 'border-red-400' : 'border-gray-300'"
                                />
                                <p v-if="serverErrors.rfc" class="text-xs text-red-500 mt-1">{{ serverErrors.rfc }}</p>
                            </div>

                            <!-- Email -->
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">
                                    Correo electrónico <span class="text-red-500">*</span>
                                </label>
                                <input
                                    v-model="form.email"
                                    type="email"
                                    placeholder="tucorreo@ejemplo.com"
                                    class="w-full border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-[#621134]/40"
                                    :class="serverErrors.email ? 'border-red-400' : 'border-gray-300'"
                                />
                                <p v-if="serverErrors.email" class="text-xs text-red-500 mt-1">{{ serverErrors.email }}</p>
                            </div>

                            <!-- Teléfono -->
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">
                                    Teléfono celular
                                    <span class="text-gray-400 font-normal text-xs">(opcional — para recibir la factura por WhatsApp)</span>
                                </label>
                                <input
                                    v-model="form.phone"
                                    type="tel"
                                    maxlength="10"
                                    placeholder="10 dígitos"
                                    class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-[#621134]/40"
                                />
                            </div>

                            <!-- Nombre -->
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">
                                    Nombre completo <span class="text-gray-400 font-normal text-xs">(opcional)</span>
                                </label>
                                <input
                                    v-model="form.name"
                                    type="text"
                                    placeholder="Como aparece en tu constancia fiscal"
                                    class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-[#621134]/40"
                                />
                            </div>

                            <!-- Razón social -->
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">
                                    Razón social <span class="text-gray-400 font-normal text-xs">(opcional, solo para personas morales)</span>
                                </label>
                                <input
                                    v-model="form.business_name"
                                    type="text"
                                    placeholder="Nombre de la empresa"
                                    class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-[#621134]/40"
                                />
                            </div>

                            <!-- Régimen fiscal -->
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">
                                    Régimen fiscal <span class="text-red-500">*</span>
                                </label>
                                <select
                                    class="w-full border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-[#621134]/40 bg-white"
                                    :class="serverErrors.fiscal_regimen_id ? 'border-red-400' : 'border-gray-300'"
                                    @change="onRegimeChange(fiscalRegimes.find(r => r.id == $event.target.value))"
                                >
                                    <option value="">Selecciona tu régimen fiscal…</option>
                                    <option
                                        v-for="regime in fiscalRegimes"
                                        :key="regime.id"
                                        :value="regime.id"
                                    >
                                        {{ regime.code }} — {{ regime.name }}
                                    </option>
                                </select>
                                <p v-if="serverErrors.fiscal_regimen_id" class="text-xs text-red-500 mt-1">{{ serverErrors.fiscal_regimen_id }}</p>
                            </div>

                            <!-- Uso del CFDI -->
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">
                                    Uso del CFDI <span class="text-red-500">*</span>
                                </label>
                                <div v-if="loadingCfdi" class="text-sm text-gray-400 py-2">Cargando usos disponibles…</div>
                                <select
                                    v-else
                                    class="w-full border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-[#621134]/40 bg-white"
                                    :class="serverErrors.cfdi_use_id ? 'border-red-400' : 'border-gray-300'"
                                    :disabled="!form.fiscal_regimen_id"
                                    @change="onCfdiChange(cfdiUses.find(u => u.id == $event.target.value))"
                                >
                                    <option value="">{{ form.fiscal_regimen_id ? 'Selecciona el uso…' : 'Primero selecciona el régimen' }}</option>
                                    <option
                                        v-for="use in cfdiUses"
                                        :key="use.id"
                                        :value="use.id"
                                    >
                                        {{ use.code }} — {{ use.name }}
                                    </option>
                                </select>
                                <p v-if="serverErrors.cfdi_use_id" class="text-xs text-red-500 mt-1">{{ serverErrors.cfdi_use_id }}</p>
                            </div>

                            <!-- Código postal fiscal -->
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">
                                    Código postal fiscal <span class="text-red-500">*</span>
                                </label>
                                <input
                                    v-model="form.fiscal_postal_code"
                                    type="text"
                                    maxlength="5"
                                    placeholder="5 dígitos"
                                    class="w-full border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-[#621134]/40"
                                    :class="serverErrors.fiscal_postal_code ? 'border-red-400' : 'border-gray-300'"
                                />
                                <p v-if="serverErrors.fiscal_postal_code" class="text-xs text-red-500 mt-1">{{ serverErrors.fiscal_postal_code }}</p>
                            </div>

                            <!-- Dirección -->
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">
                                    Dirección <span class="text-gray-400 font-normal text-xs">(opcional)</span>
                                </label>
                                <input
                                    v-model="form.address"
                                    type="text"
                                    placeholder="Calle, número, colonia"
                                    class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-[#621134]/40"
                                />
                            </div>

                            <!-- Botón enviar -->
                            <div class="pt-2">
                                <button
                                    type="submit"
                                    class="w-full py-3 rounded-lg text-white font-semibold text-sm bg-[#621134] hover:bg-[#7a1540] disabled:opacity-50 transition-colors"
                                    :disabled="submitting"
                                >
                                    <span v-if="submitting">Enviando solicitud…</span>
                                    <span v-else>Solicitar mi factura</span>
                                </button>
                            </div>

                        </form>
                    </div>

                    <p class="text-xs text-center text-gray-400 pb-4">
                        Al enviar aceptas que tus datos sean utilizados únicamente para la emisión de la factura electrónica.
                    </p>
                </template>

            </div>
        </main>

        <!-- Pie -->
        <footer class="bg-white border-t py-3 px-4 text-center text-xs text-gray-400">
            H. Ayuntamiento de Comalcalco — Dirección de Tránsito Municipal
        </footer>

    </div>
</template>
