import { api, apiURL } from '@Services/Api';

const reportService = {
    /**
     * Fetches the top selling product.
     * @param {string|null} fromDate - Start date in YYYY-MM-DD format.
     * @param {string|null} toDate - End date in YYYY-MM-DD format.
     * @returns {Promise<Object>}
     */
    async getTopSellingProduct(fromDate = null, toDate = null) {
        return new Promise((resolve, reject) => {
            const params = {};
            if (fromDate) params.from_date = fromDate;
            if (toDate) params.to_date = toDate;

            api.get(apiURL('reports/top-selling-product'), {
                params,
                onSuccess: (response) => {
                    resolve(response);
                },
                onError: (error) => {
                    console.error('Error al cargar el producto más vendido:', error);
                    reject(error);
                }
            });
        });
    },

    /**
     * Fetches products without movement.
     * @param {string|null} fromDate - Start date in YYYY-MM-DD format.
     * @param {string|null} toDate - End date in YYYY-MM-DD format.
     * @param {boolean} includeStockValue - Flag to include the inventory value in the response.
     * @param {number} page - Page number for pagination.
     * @returns {Promise<Object>}
     */
    async getProductsWithoutMovement(fromDate = null, toDate = null, includeStockValue = true, page = 1) {
        return new Promise((resolve, reject) => {
            const params = {
                include_stock_value: includeStockValue ? 1 : 0,
                page
            };

            if(fromDate) params.from_date = fromDate;
            if(toDate) params.to_date = toDate;

            api.get(apiURL('reports/products-without-movement'), {
                params,
                onSuccess: (response) => {
                    resolve(response);
                },
                onError: (error) => {
                    console.error('Error al cargar los productos sin movimiento:', error);
                    reject(error);
                }
            });
        });
    },

    /**
     * Exports inventory report to Excel file.
     * @param {Object} filters - Optional filters for the export.
     * @param {number|null} filters.category_id - Filter by category ID.
     * @param {boolean|null} filters.with_serials_only - Only products with serial number tracking.
     * @param {number|null} filters.low_stock_threshold - Filter products below this stock level.
     * @returns {Promise<void>}
     */
    async exportInventoryToExcel(filters = {}) {
        try {
            // Construir URL con parámetros
            let url = apiURL('reports/inventory/excel');
            const params = [];

            if (filters.category_id) params.push(`category_id=${filters.category_id}`);
            if (filters.with_serials_only !== undefined) params.push(`with_serials_only=${filters.with_serials_only ? 'true' : 'false'}`);
            if (filters.low_stock_threshold) params.push(`low_stock_threshold=${filters.low_stock_threshold}`);
            if (filters.fecha_inicio) params.push(`fecha_inicio=${encodeURIComponent(filters.fecha_inicio)}`);
            if (filters.fecha_fin) params.push(`fecha_fin=${encodeURIComponent(filters.fecha_fin)}`);
            if (filters.q) params.push(`q=${encodeURIComponent(filters.q)}`);

            if (params.length > 0) {
                url += `?${params.join('&')}`;
            }

            // Hacer petición con axios para descargar archivo
            const response = await window.axios.get(url, {
                responseType: 'blob',
                headers: {
                    'Authorization': `Bearer ${sessionStorage.token}`,
                }
            });

            // Crear blob
            const blob = new Blob([response.data], {
                type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
            });

            // Generar el nombre del archivo con fecha actual
            const now = new Date();
            const timestamp = now.toISOString().split('T')[0]; // YYYY-MM-DD
            const filename = `inventario_${timestamp}.xlsx`;

            // Crear URL del blob
            const downloadUrl = window.URL.createObjectURL(blob);

            // Crear elemento <a> temporal para descargar
            const link = document.createElement('a');
            link.href = downloadUrl;
            link.download = filename;
            document.body.appendChild(link);
            link.click();

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

            return Promise.resolve();
        } catch (error) {
            console.error('Error al exportar inventario:', error);

            // Manejar errores de blob
            if (error.response && error.response.data instanceof Blob) {
                const text = await error.response.data.text();
                try {
                    const json = JSON.parse(text);
                    return Promise.reject(new Error(json.message || 'Error al exportar el reporte'));
                } catch {
                    return Promise.reject(new Error('Error al exportar el reporte'));
                }
            }

            return Promise.reject(error);
        }
    },

    /**
     * Exports kardex report to Excel file.
     * @param {Object} filters - Filters for the export.
     * @param {number} filters.inventory_id - Product ID (required).
     * @param {string} filters.fecha_inicio - Start date YYYY-MM-DD (required).
     * @param {string} filters.fecha_fin - End date YYYY-MM-DD (required).
     * @param {number|null} filters.warehouse_id - Filter by warehouse.
     * @param {string|null} filters.movement_type - Filter by type: entry, exit, transfer, sale, return.
     * @returns {Promise<void>}
     */
    async exportKardexToExcel(filters = {}) {
        try {
            let url = apiURL('reports/kardex/excel');
            const params = [];

            if (filters.inventory_id) params.push(`inventory_id=${filters.inventory_id}`);
            if (filters.fecha_inicio) params.push(`fecha_inicio=${encodeURIComponent(filters.fecha_inicio)}`);
            if (filters.fecha_fin) params.push(`fecha_fin=${encodeURIComponent(filters.fecha_fin)}`);
            if (filters.warehouse_id) params.push(`warehouse_id=${filters.warehouse_id}`);
            if (filters.movement_type) params.push(`movement_type=${encodeURIComponent(filters.movement_type)}`);

            if (params.length > 0) {
                url += `?${params.join('&')}`;
            }

            const response = await window.axios.get(url, {
                responseType: 'blob',
                headers: {
                    'Authorization': `Bearer ${sessionStorage.token}`,
                }
            });

            const blob = new Blob([response.data], {
                type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
            });

            const now = new Date();
            const timestamp = now.toISOString().split('T')[0];
            const filename = `kardex_${timestamp}.xlsx`;

            const downloadUrl = window.URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.href = downloadUrl;
            link.download = filename;
            document.body.appendChild(link);
            link.click();

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

            return Promise.resolve();
        } catch (error) {
            console.error('Error al exportar kardex:', error);

            if (error.response && error.response.data instanceof Blob) {
                const text = await error.response.data.text();
                try {
                    const json = JSON.parse(text);
                    return Promise.reject(new Error(json.message || 'Error al exportar el kardex'));
                } catch {
                    return Promise.reject(new Error('Error al exportar el kardex'));
                }
            }

            return Promise.reject(error);
        }
    }
};

export default reportService;