<script setup>
import { ref, watch, computed } from 'vue';
import { useForm, useApi } from '@Services/Api';
import { apiTo } from '../Module';

import DialogModal    from '@Holos/DialogModal.vue';
import PrimaryButton  from '@Holos/Button/Primary.vue';
import SecondaryButton from '@Holos/Button/Secondary.vue';
import SingleFile     from '@Holos/Form/SingleFile.vue';
import Input          from '@Holos/Form/Input.vue';
import Textarea       from '@Holos/Form/Textarea.vue';
import GoogleIcon     from '@Shared/GoogleIcon.vue';


/** Props */
const props = defineProps({
    show:    Boolean,
    model:   Object,
    loading: Boolean,
});

/** Eventos */
const emit = defineEmits(['close', 'updated']);

/** API para cambio de estado */
const apiStatus = useApi();

/** Formulario de subida CFDI */
const invoiceForm = ref(useForm({
    xml_file:   null,
    pdf_file:   null,
    folio:      '',
    uuid:       '',
    stamped_at: '',
    notes:      '',
}));

/** Resetear formulario cuando se abre el modal */
watch(() => props.show, (open) => {
    if (open) {
        invoiceForm.value = useForm({
            xml_file:   null,
            pdf_file:   null,
            folio:      '',
            uuid:       '',
            stamped_at: '',
            notes:      '',
        });
    }
});

const statusConfig = {
    pending:    { label: 'Pendiente',  cls: 'bg-yellow-100 text-yellow-800' },
    processing: { label: 'En proceso', cls: 'bg-blue-100 text-blue-800'     },
    completed:  { label: 'Completada', cls: 'bg-green-100 text-green-800'   },
    rejected:   { label: 'Rechazada',  cls: 'bg-red-100 text-red-800'       },
};

const canChangeStatus = computed(() =>
    props.model?.status === 'pending' || props.model?.status === 'processing'
);

const canUpload = computed(() =>
    props.model?.status !== 'completed' && props.model?.status !== 'rejected'
);

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

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

/** Cambiar estado */
const changeStatus = (status) => {
    apiStatus.put(apiTo(props.model.id, 'status'), {
        data: { status },
        onSuccess: (data) => {
            Notify.success(
                status === 'processing'
                    ? 'Solicitud marcada como "En proceso".'
                    : 'Solicitud rechazada.'
            );
            emit('updated', data.model);
            emit('close');
        },
        onFail: (data) => {
            Notify.warning(data?.message ?? 'No se pudo cambiar el estado.');
        }
    });
};

/** Subir CFDI */
const uploadInvoice = () => {
    if (!invoiceForm.value.xml_file && !invoiceForm.value.pdf_file) {
        Notify.warning('Debes adjuntar al menos el archivo XML o el PDF del CFDI.');
        return;
    }

    invoiceForm.value.post(apiTo(props.model.id, 'invoice'), {
        onSuccess: (data) => {
            Notify.success(data?.message ?? 'Factura subida y enviada al ciudadano.');
            emit('updated', data.model);
            emit('close');
        },
        onError: () => {
            Notify.error('Error al subir los archivos. Verifica el formulario.');
        }
    });
};
</script>

<template>
    <DialogModal
        :show="show"
        max-width="2xl"
        @close="emit('close')"
    >
        <template #title>
            <div class="flex items-center gap-3 py-1">
                <span class="font-bold text-xl">
                    Solicitud de Factura #{{ model?.id }}
                </span>
                <span
                    v-if="model?.status"
                    class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium"
                    :class="statusConfig[model.status]?.cls"
                >
                    {{ statusConfig[model.status]?.label }}
                </span>
            </div>
        </template>

        <template #content>
            <!-- Cargando -->
            <div v-if="loading" class="flex justify-center py-10">
                <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
            </div>

            <div v-else-if="model?.id" class="px-4 pt-2 pb-4 space-y-5">

                <!-- ── Datos del ciudadano ── -->
                <section>
                    <h3 class="text-sm font-semibold text-gray-500 uppercase tracking-wider mb-2 border-b pb-1">
                        Datos del ciudadano
                    </h3>
                    <div class="grid grid-cols-2 gap-x-6 gap-y-2 text-sm">
                        <div><span class="text-gray-500">RFC:</span> <span class="font-mono font-medium">{{ model.rfc }}</span></div>
                        <div><span class="text-gray-500">Nombre:</span> {{ model.name || '—' }}</div>
                        <div><span class="text-gray-500">Email:</span> {{ model.email }}</div>
                        <div><span class="text-gray-500">Teléfono:</span> {{ model.phone || '—' }}</div>
                        <div><span class="text-gray-500">Razón social:</span> {{ model.business_name || '—' }}</div>
                        <div><span class="text-gray-500">C.P. fiscal:</span> {{ model.fiscal_postal_code }}</div>
                        <div class="col-span-2"><span class="text-gray-500">Dirección:</span> {{ model.address || '—' }}</div>
                    </div>
                </section>

                <!-- ── Datos fiscales ── -->
                <section>
                    <h3 class="text-sm font-semibold text-gray-500 uppercase tracking-wider mb-2 border-b pb-1">
                        Datos fiscales
                    </h3>
                    <div class="grid grid-cols-1 gap-y-2 text-sm">
                        <div>
                            <span class="text-gray-500">Régimen fiscal:</span>
                            <span v-if="model.fiscal_regime" class="ml-1">
                                <span class="font-mono font-medium">{{ model.fiscal_regime.code }}</span>
                                — {{ model.fiscal_regime.name }}
                            </span>
                            <span v-else> —</span>
                        </div>
                        <div>
                            <span class="text-gray-500">Uso del CFDI:</span>
                            <span v-if="model.cfdi_use" class="ml-1">
                                <span class="font-mono font-medium">{{ model.cfdi_use.code }}</span>
                                — {{ model.cfdi_use.name }}
                            </span>
                            <span v-else> —</span>
                        </div>
                    </div>
                </section>

                <!-- ── Pago relacionado ── -->
                <section>
                    <h3 class="text-sm font-semibold text-gray-500 uppercase tracking-wider mb-2 border-b pb-1">
                        Pago relacionado
                    </h3>
                    <div class="grid grid-cols-2 gap-x-6 gap-y-2 text-sm">
                        <div><span class="text-gray-500">Monto:</span> <span class="font-medium text-green-700">{{ formatAmount(model.payment?.total_amount) }}</span></div>
                        <div><span class="text-gray-500">Pagado el:</span> {{ formatDate(model.payment?.paid_at) }}</div>
                        <div><span class="text-gray-500">Infractor:</span> {{ model.payment?.model?.name || '—' }}</div>
                        <div><span class="text-gray-500">Placa:</span> <span class="font-mono">{{ model.payment?.model?.plate || '—' }}</span></div>
                        <div><span class="text-gray-500">CURP:</span> <span class="font-mono text-xs">{{ model.payment?.model?.curp || '—' }}</span></div>
                    </div>

                    <!-- Conceptos de cargo -->
                    <div v-if="model.payment?.model?.charge_concepts?.length" class="mt-3">
                        <p class="text-xs font-semibold text-gray-500 mb-1">Conceptos de cargo:</p>
                        <div class="space-y-1">
                            <div
                                v-for="cc in model.payment.model.charge_concepts"
                                :key="cc.id"
                                class="flex justify-between items-center bg-gray-50 rounded px-3 py-1.5 text-xs"
                            >
                                <div>
                                    <span class="font-medium">{{ cc.name }}</span>
                                    <span class="text-gray-500 ml-1">({{ cc.article }})</span>
                                </div>
                                <span class="font-medium text-gray-700">
                                    {{ formatAmount(cc.pivot?.override_amount) }}
                                </span>
                            </div>
                        </div>
                    </div>
                </section>

                <!-- ── Factura ya generada ── -->
                <section v-if="model.invoice">
                    <h3 class="text-sm font-semibold text-gray-500 uppercase tracking-wider mb-2 border-b pb-1">
                        Factura generada
                    </h3>
                    <div class="grid grid-cols-2 gap-x-6 gap-y-2 text-sm">
                        <div><span class="text-gray-500">Folio:</span> <span class="font-mono font-medium">{{ model.invoice.folio || '—' }}</span></div>
                        <div><span class="text-gray-500">Timbrada el:</span> {{ formatDate(model.invoice.stamped_at) }}</div>
                        <div class="col-span-2">
                            <span class="text-gray-500">UUID SAT:</span>
                            <span class="font-mono text-xs ml-1">{{ model.invoice.uuid || '—' }}</span>
                        </div>
                        <div v-if="model.invoice.notes" class="col-span-2">
                            <span class="text-gray-500">Notas:</span> {{ model.invoice.notes }}
                        </div>
                    </div>
                    <div class="flex gap-3 mt-3">
                        <a
                            v-if="model.invoice.xml_url"
                            :href="model.invoice.xml_url"
                            target="_blank"
                            class="inline-flex items-center gap-1 text-sm text-blue-600 hover:underline"
                        >
                            <GoogleIcon
                                class="text-base"
                                name="code"
                            />
                            Descargar XML
                        </a>
                        <a
                            v-if="model.invoice.pdf_url"
                            :href="model.invoice.pdf_url"
                            target="_blank"
                            class="inline-flex items-center gap-1 text-sm text-red-600 hover:underline"
                        >
                            <GoogleIcon
                                class="text-base"
                                name="picture_as_pdf"
                            />
                            Descargar PDF
                        </a>
                    </div>
                </section>

                <!-- ── Cambiar estado ── -->
                <section v-if="canChangeStatus">
                    <h3 class="text-sm font-semibold text-gray-500 uppercase tracking-wider mb-2 border-b pb-1">
                        Cambiar estado
                    </h3>
                    <div class="flex flex-wrap gap-2">
                        <button
                            v-if="model.status === 'pending'"
                            class="inline-flex items-center gap-1 px-4 py-1.5 rounded text-sm font-medium bg-blue-600 text-white hover:bg-blue-700 disabled:opacity-50 transition-colors"
                            :disabled="apiStatus.processing"
                            @click="changeStatus('processing')"
                        >
                            Marcar en proceso
                        </button>
                        <button
                            class="inline-flex items-center gap-1 px-4 py-1.5 rounded text-sm font-medium bg-red-600 text-white hover:bg-red-700 disabled:opacity-50 transition-colors"
                            :disabled="apiStatus.processing"
                            @click="changeStatus('rejected')"
                        >
                            Rechazar solicitud
                        </button>
                    </div>
                </section>

                <!-- ── Subir CFDI ── -->
                <section v-if="canUpload">
                    <h3 class="text-sm font-semibold text-gray-500 uppercase tracking-wider mb-3 border-b pb-1">
                        Subir CFDI (XML / PDF)
                    </h3>
                    <div class="space-y-3">
                        <div class="grid grid-cols-2 gap-4">
                            <SingleFile
                                v-model="invoiceForm.xml_file"
                                title="Archivo XML"
                                accept=".xml,text/xml,application/xml"
                            />
                            <SingleFile
                                v-model="invoiceForm.pdf_file"
                                title="Archivo PDF"
                                accept=".pdf,application/pdf"
                            />
                        </div>
                        <div class="grid grid-cols-2 gap-4">
                            <Input
                                v-model="invoiceForm.folio"
                                id="Folio"
                                placeholder="Ej. A-0001"
                            />
                            <Input
                                v-model="invoiceForm.uuid"
                                id="UUID del timbre"
                                placeholder="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
                            />
                        </div>
                        <div class="grid grid-cols-2 gap-4">
                            <Input
                                v-model="invoiceForm.stamped_at"
                                id="Fecha de timbrado"
                                type="datetime-local"
                            />
                            <div></div>
                        </div>
                        <Textarea
                            v-model="invoiceForm.notes"
                            id="Notas internas"
                            placeholder="Ej. Generado con PAC Facturama"
                        />
                        <div class="pt-1">
                            <button
                                class="inline-flex items-center gap-2 px-5 py-2 rounded text-sm font-medium bg-green-600 text-white hover:bg-green-700 disabled:opacity-50 transition-colors"
                                :disabled="invoiceForm.processing"
                                @click="uploadInvoice"
                            >
                                <span v-if="invoiceForm.processing">Subiendo…</span>
                                <span v-else>Subir y enviar al ciudadano</span>
                            </button>
                        </div>
                    </div>
                </section>

            </div>
        </template>

        <template #footer>
            <SecondaryButton @click="emit('close')">
                Cerrar
            </SecondaryButton>
        </template>
    </DialogModal>
</template>
