<script setup>
import { ref } from 'vue';
import { useForm, apiURL } from '@Services/Api';

import Modal from '@Holos/Modal.vue';
import GoogleIcon from '@Shared/GoogleIcon.vue';

/** Props */
const props = defineProps({
    show: {
        type: Boolean,
        required: true
    },
    request: {
        type: Object,
        required: true
    }
});

/** Emits */
const emit = defineEmits(['close', 'refresh']);

/** Estado */
const processing = ref(false);
const uploadForm = useForm({
    invoice_xml: null,
    invoice_pdf: null,
    cfdi_uuid: ''
});

/** Métodos */
const closeModal = () => {
    uploadForm.reset();
    emit('close');
};

const handleXmlChange = (event) => {
    const file = event.target.files[0];
    if (file) {
        if (file.name.endsWith('.xml') || file.type === 'text/xml' || file.type === 'application/xml') {
            uploadForm.invoice_xml = file;
        } else {
            window.Notify.warning('Por favor selecciona un archivo XML válido');
            event.target.value = '';
        }
    }
};

const handlePdfChange = (event) => {
    const file = event.target.files[0];
    if (file) {
        if (file.name.endsWith('.pdf') || file.type === 'application/pdf') {
            uploadForm.invoice_pdf = file;
        } else {
            window.Notify.warning('Por favor selecciona un archivo PDF válido');
            event.target.value = '';
        }
    }
};

const submitUpload = () => {
    // Debug: ver qué datos se van a enviar
    console.log('Datos del formulario antes de enviar:', {
        invoice_xml: uploadForm.invoice_xml,
        invoice_pdf: uploadForm.invoice_pdf,
        cfdi_uuid: uploadForm.cfdi_uuid
    });

    // Validación: al menos debe haber PDF
    if (!uploadForm.invoice_pdf) {
        window.Notify.warning('Por favor selecciona el archivo PDF');
        return;
    }

    processing.value = true;

    // Crear FormData manualmente para mayor control
    const formData = new FormData();

    // Agregar archivos si existen
    if (uploadForm.invoice_xml) {
        formData.append('xml_file', uploadForm.invoice_xml, uploadForm.invoice_xml.name);
        console.log('XML agregado:', uploadForm.invoice_xml.name);
    }

    if (uploadForm.invoice_pdf) {
        formData.append('invoice_pdf', uploadForm.invoice_pdf, uploadForm.invoice_pdf.name);
        console.log('PDF agregado:', uploadForm.invoice_pdf.name, 'Tamaño:', uploadForm.invoice_pdf.size, 'bytes');
    }

    // Agregar UUID si existe
    if (uploadForm.cfdi_uuid && uploadForm.cfdi_uuid.trim()) {
        formData.append('cfdi_uuid', uploadForm.cfdi_uuid.trim());
        console.log('UUID agregado:', uploadForm.cfdi_uuid);
    }

    // Enviar con axios directamente
    window.axios({
        method: 'POST',
        url: apiURL(`invoice-requests/${props.request.id}/upload`),
        data: formData,
        headers: {
            'Content-Type': 'multipart/form-data',
            'Accept': 'application/json',
            'Authorization': `Bearer ${sessionStorage.token}`,
            'X-CSRF-TOKEN': localStorage.csrfToken
        }
    })
    .then(response => {
        console.log('Respuesta exitosa:', response.data);
        if (response.data.status === 'success') {
            window.Notify.success('Archivos de factura subidos correctamente');
            uploadForm.reset();
            emit('refresh');
            emit('close');
        } else if (response.data.status === 'fail') {
            console.error('Error del backend:', response.data);
            window.Notify.error(response.data.data?.message || 'Error al subir los archivos');
        }
    })
    .catch(error => {
        console.error('Error completo:', error);
        console.error('Respuesta del servidor:', error.response?.data);

        if (error.response?.status === 422) {
            // Errores de validación
            const errors = error.response.data.errors || {};
            console.error('Errores de validación:', errors);
            window.Notify.error(Object.values(errors).flat().join(', '));
        } else {
            window.Notify.error(error.response?.data?.message || 'Error al subir los archivos');
        }
    })
    .finally(() => {
        processing.value = false;
    });
};
</script>

<template>
    <Modal :show="show" max-width="lg" @close="closeModal">
        <div class="p-6">
            <!-- Header -->
            <div class="flex items-center gap-3 mb-6">
                <div class="flex items-center justify-center w-12 h-12 rounded-full bg-blue-100 dark:bg-blue-900/30">
                    <GoogleIcon name="upload_file" class="text-2xl text-blue-600 dark:text-blue-400" />
                </div>
                <div class="flex-1">
                    <h3 class="text-lg font-bold text-gray-900 dark:text-gray-100">
                        Subir Archivos de Factura
                    </h3>
                    <p class="text-sm text-gray-500 dark:text-gray-400">
                        Solicitud #{{ request.id }} - {{ request.client?.name }}
                    </p>
                </div>
                <button
                    @click="closeModal"
                    :disabled="processing"
                    class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors disabled:opacity-50"
                >
                    <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="M6 18L18 6M6 6l12 12"/>
                    </svg>
                </button>
            </div>

            <!-- Información de la venta -->
            <div class="mb-6 p-4 bg-gray-50 dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700">
                <div class="flex items-center gap-2 mb-2">
                    <GoogleIcon name="receipt_long" class="text-lg text-gray-600 dark:text-gray-400" />
                    <span class="text-sm font-semibold text-gray-700 dark:text-gray-300">
                        Folio: {{ request.sale?.invoice_number || 'N/A' }}
                    </span>
                </div>
                <div class="text-xs text-gray-600 dark:text-gray-400">
                    RFC: <span class="font-mono font-semibold">{{ request.client?.rfc || 'N/A' }}</span>
                </div>
            </div>

            <!-- Formulario -->
            <form @submit.prevent="submitUpload" class="space-y-5">
                <!-- UUID del CFDI -->
                <div>
                    <label class="flex items-center gap-2 text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2">
                        <GoogleIcon name="key" class="text-lg text-purple-600 dark:text-purple-400" />
                        UUID del CFDI
                    </label>
                    <input
                        v-model="uploadForm.cfdi_uuid"
                        type="text"
                        placeholder="Ej: 123e4567-e89b-12d3-a456-426614174000"
                        :disabled="processing"
                        class="w-full px-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 placeholder-gray-400 dark:placeholder-gray-500 focus:ring-2 focus:ring-purple-500 focus:border-transparent disabled:opacity-50 disabled:cursor-not-allowed transition-colors font-mono text-sm"
                    />
                    <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                        Identificador único del CFDI timbrado
                    </p>
                </div>

                <!-- Archivo XML -->
                <div>
                    <label class="flex items-center gap-2 text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2">
                        <GoogleIcon name="description" class="text-lg text-blue-600 dark:text-blue-400" />
                        Archivo XML
                    </label>
                    <div class="relative">
                        <input
                            type="file"
                            accept=".xml,application/xml,text/xml"
                            :disabled="processing"
                            @change="handleXmlChange"
                            class="w-full text-sm text-gray-500 dark:text-gray-400
                                   file:mr-4 file:py-2.5 file:px-4
                                   file:rounded-lg file:border-0
                                   file:text-sm file:font-semibold
                                   file:bg-blue-50 file:text-blue-700
                                   hover:file:bg-blue-100
                                   file:cursor-pointer
                                   dark:file:bg-blue-900/30 dark:file:text-blue-400
                                   dark:hover:file:bg-blue-900/50
                                   file:transition-colors
                                   disabled:opacity-50 disabled:cursor-not-allowed"
                        />
                        <GoogleIcon
                            v-if="uploadForm.invoice_xml"
                            name="check_circle"
                            class="absolute right-3 top-1/2 -translate-y-1/2 text-2xl text-green-500"
                        />
                    </div>
                    <p v-if="uploadForm.invoice_xml" class="mt-2 flex items-center gap-2 text-xs">
                        <GoogleIcon name="insert_drive_file" class="text-base text-blue-600 dark:text-blue-400" />
                        <span class="font-medium text-gray-700 dark:text-gray-300">{{ uploadForm.invoice_xml.name }}</span>
                        <span class="text-gray-500 dark:text-gray-400">
                            ({{ (uploadForm.xml_file.size / 1024).toFixed(2) }} KB)
                        </span>
                    </p>
                    <p v-else class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                        Archivo XML del CFDI timbrado por el PAC
                    </p>
                </div>

                <!-- Archivo PDF -->
                <div>
                    <label class="flex items-center gap-2 text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2">
                        <GoogleIcon name="picture_as_pdf" class="text-lg text-red-600 dark:text-red-400" />
                        Archivo PDF
                    </label>
                    <div class="relative">
                        <input
                            type="file"
                            accept=".pdf,application/pdf"
                            :disabled="processing"
                            @change="handlePdfChange"
                            class="w-full text-sm text-gray-500 dark:text-gray-400
                                   file:mr-4 file:py-2.5 file:px-4
                                   file:rounded-lg file:border-0
                                   file:text-sm file:font-semibold
                                   file:bg-red-50 file:text-red-700
                                   hover:file:bg-red-100
                                   file:cursor-pointer
                                   dark:file:bg-red-900/30 dark:file:text-red-400
                                   dark:hover:file:bg-red-900/50
                                   file:transition-colors
                                   disabled:opacity-50 disabled:cursor-not-allowed"
                        />
                        <GoogleIcon
                            v-if="uploadForm.invoice_pdf"
                            name="check_circle"
                            class="absolute right-3 top-1/2 -translate-y-1/2 text-2xl text-green-500"
                        />
                    </div>
                    <p v-if="uploadForm.invoice_pdf" class="mt-2 flex items-center gap-2 text-xs">
                        <GoogleIcon name="picture_as_pdf" class="text-base text-red-600 dark:text-red-400" />
                        <span class="font-medium text-gray-700 dark:text-gray-300">{{ uploadForm.invoice_pdf.name }}</span>
                        <span class="text-gray-500 dark:text-gray-400">
                            ({{ (uploadForm.invoice_pdf.size / 1024).toFixed(2) }} KB)
                        </span>
                    </p>
                    <p v-else class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                        Representación impresa del CFDI en formato PDF
                    </p>
                </div>

                <!-- Nota informativa -->
                <div class="flex gap-3 p-4 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg">
                    <GoogleIcon name="info" class="text-xl text-blue-600 dark:text-blue-400 flex-shrink-0" />
                    <div class="text-xs text-blue-800 dark:text-blue-300">
                        <p class="font-semibold mb-1">Información importante:</p>
                        <ul class="list-disc list-inside space-y-1">
                            <li>Los archivos deben corresponder a la factura timbrada</li>
                            <li>El UUID debe coincidir con el del XML timbrado</li>
                            <li>Tamaño máximo por archivo: 5MB</li>
                        </ul>
                    </div>
                </div>

                <!-- Acciones -->
                <div class="flex items-center justify-end gap-3 pt-4 border-t border-gray-200 dark:border-gray-700">
                    <button
                        type="button"
                        @click="closeModal"
                        :disabled="processing"
                        class="px-5 py-2.5 text-sm font-semibold text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-500 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                    >
                        Cancelar
                    </button>
                    <button
                        type="submit"
                        :disabled="processing"
                        class="inline-flex items-center gap-2 px-5 py-2.5 text-sm font-semibold text-white bg-gradient-to-r from-blue-600 to-purple-600 hover:from-blue-700 hover:to-purple-700 rounded-lg focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-all disabled:opacity-50 disabled:cursor-not-allowed shadow-lg shadow-blue-500/30"
                    >
                        <GoogleIcon name="upload" class="text-lg" />
                        {{ processing ? 'Subiendo...' : 'Subir Archivos' }}
                    </button>
                </div>
            </form>
        </div>
    </Modal>
</template>

<style scoped>
/* Animación para el check de archivo seleccionado */
@keyframes checkIn {
    0% {
        transform: translate(50%, -50%) scale(0);
        opacity: 0;
    }
    50% {
        transform: translate(50%, -50%) scale(1.2);
    }
    100% {
        transform: translate(50%, -50%) scale(1);
        opacity: 1;
    }
}

.absolute.right-3 {
    animation: checkIn 0.3s ease-out;
}
</style>
