import Swal from 'sweetalert2';
import {
    esValorCampoVacio,
    obtenerValorCampoContrato,
} from '../utils/validacionFormulario';

/**
 * Configuración de campos a validar por tipo de CUPS
 */
export interface CupsValidationConfig {
    // Campos obligatorios para CUPS Eléctrico
    electricoRequired?: string[];
    // Campos obligatorios para CUPS Gas
    gasRequired?: string[];
    // Etiquetas personalizadas para los campos (opcional)
    fieldLabels?: { [key: string]: string };
}

/**
 * Resultado de la validación
 */
export interface ValidationResult {
    isValid: boolean;
    errors: {
        electrico: ValidationError[];
        gas: ValidationError[];
    };
    totalErrors: number;
}

/**
 * Error de validación por fila
 */
export interface ValidationError {
    rowIndex: number;
    cups: string;
    cliente: string;
    missingFields: string[];
}

/**
 * Hook para validar registros de CUPS antes de guardar
 * Permite configurar campos obligatorios manualmente
 */
export function useValidateCupsBeforeSave(config?: CupsValidationConfig) {
    // Configuración por defecto de campos obligatorios
    const defaultElectricoFields = [
        'comercializadora',
        'producto',
        'anexo',
        'cups_electrico',
        'fechaInicio',
        'fechaFin',
        'tarifa'
    ];

    const defaultGasFields = [
        'comercializadora',
        'producto',
        'anexo',
        'cupsGas',
        'fechaInicio',
        'fechaFin',
        'tarifaGas'
    ];

    // Etiquetas por defecto para los campos
    const defaultLabels: { [key: string]: string } = {
        comercializadora: 'Comercializadora',
        producto: 'Producto',
        anexo: 'Anexo',
        cups_electrico: 'CUPS Eléctrico',
        codigoCups: 'Código CUPS',
        cupsGas: 'CUPS Gas',
        fechaInicio: 'Fecha Inicio',
        fechaFin: 'Fecha Fin',
        tarifa: 'Tarifa',
        tarifaGas: 'Tarifa Gas',
        tipoprecio: 'Tipo de Precio',
        documento_fiscal: 'Documento Fiscal',
        razon_social: 'Razón Social'
    };

    // Usar configuración proporcionada o valores por defecto
    const electricoRequiredFields = config?.electricoRequired || defaultElectricoFields;
    const gasRequiredFields = config?.gasRequired || defaultGasFields;
    const fieldLabels = { ...defaultLabels, ...(config?.fieldLabels || {}) };

    /**
     * Valida un registro individual de CUPS
     */
    const validateRow = (row: any, requiredFields: string[], rowIndex: number): ValidationError | null => {
        const missingFields: string[] = [];

        requiredFields.forEach(field => {
            const value = obtenerValorCampoContrato(row, field);

            // Verificar si el campo está vacío, null o undefined
            // NOTA: Ya NO consideramos '0' como vacío, solo string vacío ''
            if (esValorCampoVacio(value)) {
                const label = fieldLabels[field] || field;
                missingFields.push(label);
            }
        });

        if (missingFields.length > 0) {
            return {
                rowIndex: rowIndex + 1, // +1 para mostrar índice humano
                cups: row.cups_electrico || row.codigoCups || row.cupsGas || 'Sin CUPS',
                cliente: row.razon_social || row.documento_fiscal || 'Sin cliente',
                missingFields
            };
        }

        return null;
    };

    /**
     * Valida todos los registros de CUPS (eléctrico y gas)
     */
    const validateAllCups = (data: { electrico: any[], gas: any[] }): ValidationResult => {
        const errors: ValidationResult = {
            isValid: true,
            errors: {
                electrico: [],
                gas: []
            },
            totalErrors: 0
        };

        // Validar CUPS Eléctricos
        data.electrico.forEach((row, index) => {
            const error = validateRow(row, electricoRequiredFields, index);
            if (error) {
                errors.errors.electrico.push(error);
                errors.totalErrors++;
            }
        });

        // Validar CUPS Gas
        data.gas.forEach((row, index) => {
            const error = validateRow(row, gasRequiredFields, index);
            if (error) {
                errors.errors.gas.push(error);
                errors.totalErrors++;
            }
        });

        errors.isValid = errors.totalErrors === 0;

        return errors;
    };

    /**
     * Genera mensaje HTML con los errores de validación
     */
    const generateErrorMessage = (validationResult: ValidationResult): string => {
        let html = '<div style="text-align: left; max-height: 400px; overflow-y: auto;">';
        html += '<p style="font-weight: bold; color: #d33; margin-bottom: 15px;">Se encontraron los siguientes errores:</p>';

        // Errores de CUPS Eléctrico
        if (validationResult.errors.electrico.length > 0) {
            html += '<div style="margin-bottom: 20px;">';
            html += '<h4 style="color: #ffc107; margin-bottom: 10px;">⚡ CUPS Eléctricos:</h4>';
            validationResult.errors.electrico.forEach(error => {
                html += `<div style="background: #f8f9fa; padding: 10px; margin-bottom: 10px; border-radius: 5px; border-left: 4px solid #ffc107;">`;
                html += `<strong>Fila ${error.rowIndex}:</strong> ${error.cliente}<br>`;
                html += `<strong>CUPS:</strong> ${error.cups}<br>`;
                html += `<strong style="color: #d33;">Faltan:</strong> ${error.missingFields.join(', ')}`;
                html += `</div>`;
            });
            html += '</div>';
        }

        // Errores de CUPS Gas
        if (validationResult.errors.gas.length > 0) {
            html += '<div style="margin-bottom: 20px;">';
            html += '<h4 style="color: #ff6b6b; margin-bottom: 10px;">🔥 CUPS Gas:</h4>';
            validationResult.errors.gas.forEach(error => {
                html += `<div style="background: #f8f9fa; padding: 10px; margin-bottom: 10px; border-radius: 5px; border-left: 4px solid #ff6b6b;">`;
                html += `<strong>Fila ${error.rowIndex}:</strong> ${error.cliente}<br>`;
                html += `<strong>CUPS:</strong> ${error.cups}<br>`;
                html += `<strong style="color: #d33;">Faltan:</strong> ${error.missingFields.join(', ')}`;
                html += `</div>`;
            });
            html += '</div>';
        }

        html += '</div>';
        return html;
    };

    /**
     * Muestra el diálogo de error con los campos faltantes
     */
    const showValidationErrorDialog = (validationResult: ValidationResult) => {
        const errorMessage = generateErrorMessage(validationResult);

        return Swal.fire({
            title: '⚠️ Validación Fallida',
            html: errorMessage,
            icon: 'error',
            confirmButtonText: 'Entendido',
            confirmButtonColor: '#d33',
            width: '600px',
            customClass: {
                popup: 'validation-error-popup',
                htmlContainer: 'validation-error-content'
            }
        });
    };

    /**
     * Ejecuta la validación y muestra errores si existen
     * Retorna true si la validación es exitosa, false si falla
     */
    const validateBeforeSave = (data: { electrico: any[], gas: any[] }): boolean => {
        // Verificar que haya al menos un registro
        if (data.electrico.length === 0 && data.gas.length === 0) {
            Swal.fire({
                title: '⚠️ Sin Registros',
                text: 'Debe agregar al menos un registro de CUPS (Eléctrico o Gas) antes de guardar.',
                icon: 'warning',
                confirmButtonText: 'Entendido',
                confirmButtonColor: '#ffc107'
            });
            return false;
        }

        // Ejecutar validación
        const validationResult = validateAllCups(data);

        // Si hay errores, mostrar diálogo
        if (!validationResult.isValid) {
            showValidationErrorDialog(validationResult);
            return false;
        }

        return true;
    };

    return {
        validateBeforeSave,
        validateAllCups,
        validateRow,
        showValidationErrorDialog
    };
}

