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

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


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

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

/** Estado */
const startDate = ref('');
const endDate = ref('');
const downloading = ref(false);

/** Métodos */
const downloadReport = () => {
    if (!startDate.value || !endDate.value) {
        window.Notify.error('Por favor selecciona ambas fechas');
        return;
    }

    if (new Date(startDate.value) > new Date(endDate.value)) {
        window.Notify.error('La fecha inicial debe ser menor a la fecha final');
        return;
    }

    downloading.value = true;

    // Construir URL con parámetros
    const url = apiURL(`reports/client-discounts/excel?fecha_inicio=${startDate.value}&fecha_fin=${endDate.value}`);

    // Hacer petición con axios para descargar archivo
    window.axios.get(url, {
        responseType: 'blob',
        headers: {
            'Authorization': `Bearer ${sessionStorage.token}`,
        }
    })
    .then(response => {
        // Crear URL del blob
        const blob = new Blob([response.data], {
            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        });
        const downloadUrl = window.URL.createObjectURL(blob);

        const link = document.createElement('a');
        link.href = downloadUrl;
        link.download = `reporte_descuentos_${startDate.value}_${endDate.value}.xlsx`;
        document.body.appendChild(link);
        link.click();

        // Limpiar
        document.body.removeChild(link);
        window.URL.revokeObjectURL(downloadUrl);

        window.Notify.success('Reporte descargado exitosamente');
    })
    .catch(async error => {
        if (error.response && error.response.data instanceof Blob) {
        const text = await error.response.data.text();
        try {
            const json = JSON.parse(text);
            window.Notify.warning(json.message || 'Error al descargar el reporte');
        } catch {
            window.Notify.error('Error al descargar el reporte');
        }
    } else {
        window.Notify.error('Error al descargar el reporte');
    }
    })
    .finally(() => {
        downloading.value = false;
    });
};

const clearDates = () => {
    startDate.value = '';
    endDate.value = '';
};

const close = () => {
    emit('close');
};
</script>

<template>
<Modal :show="show" max-width="3xl" @close="close">
    <div class="bg-white dark:bg-gray-800 rounded-lg shadow-lg p-6 relative">
        <div class="flex items-center gap-3 mb-6">
            <div class="flex items-center justify-center w-10 h-10 rounded-full bg-green-100 dark:bg-green-900/30">
                <GoogleIcon name="download" class="text-xl text-green-600 dark:text-green-400" />
            </div>
            <div>
                <h3 class="text-lg font-semibold text-gray-900 dark:text-white">
                    Reporte de Descuentos por Cliente
                </h3>
                <p class="text-sm text-gray-500 dark:text-gray-400">
                    Genera un archivo Excel con los descuentos aplicados
                </p>
            </div>
            <div class="absolute top-4 right-4">
                <button
                    @click="close"
                    class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors"
                >
                    <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>
        </div>

        <div class="space-y-4">
            <!-- Rango de Fechas -->
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                        Fecha Inicial
                    </label>
                    <input
                        v-model="startDate"
                        type="date"
                        class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
                        :disabled="downloading"
                    />
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                        Fecha Final
                    </label>
                    <input
                        v-model="endDate"
                        type="date"
                        class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
                        :disabled="downloading"
                    />
                </div>
            </div>

            <!-- Botones -->
            <div class="flex items-center gap-3">
                <PrimaryButton
                    @click="downloadReport"
                    :disabled="downloading || !startDate || !endDate"
                    class="flex items-center gap-2"
                >
                    <svg v-if="downloading" class="animate-spin h-5 w-5" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                        <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                        <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                    </svg>
                    <GoogleIcon v-else name="download" />
                    {{ downloading ? 'Generando...' : 'Descargar Excel' }}
                </PrimaryButton>

                <button
                    @click="clearDates"
                    class="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 rounded-lg transition-colors"
                    :disabled="downloading"
                >
                    Limpiar
                </button>
            </div>

            <!-- Nota informativa -->
            <div class="mt-4 p-4 bg-blue-50 dark:bg-blue-900/20 rounded-lg border border-blue-200 dark:border-blue-800">
                <div class="flex gap-2">
                    <GoogleIcon name="info" class="text-blue-600 dark:text-blue-400 text-xl flex-shrink-0" />
                    <div class="text-sm text-blue-700 dark:text-blue-300">
                        <p class="font-medium mb-1">Información del reporte:</p>
                        <ul class="list-disc list-inside space-y-1">
                            <li>Incluye descuentos aplicados en el rango seleccionado</li>
                            <li>Muestra nivel y porcentaje de descuento por cliente</li>
                            <li>Se descarga automáticamente en formato Excel (.xlsx)</li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>
</Modal>
</template>
