import { useEffect, useState } from "react";
import { Head, router, useForm, usePage } from "@inertiajs/react";
import Swal from "sweetalert2";
import { FormDataElectrico, FormDataGas, CupsOption, Localidad, Cliente, Contacto } from "../../Interfaces/Interfaces";
import { initialFormDataElectrico, initialFormDataGas } from "../../Interfaces/constants";
import { useBulkLoadCups } from "../hooks/useBulkLoadCups";
import { useLoading } from "../../../../../LoadingContext";
import { useValidateCupsBeforeSave } from "../../hooks/useValidateCupsBeforeSave";
import { getCupsElectricosByClient, getCupsGasByClient, getCupsElectricosByClientes, getCupsGasByClientes } from "../../../../../services/dataService";
import type { BulkLoadProgressControls } from '../../Shared/bulkLoadProgress';

type ContratoFormData = {
    razon_social: string;
    documento_fiscal: string;
    fecha_propuesta?: string;
    tipo_contrato: number;
    electrico: any[];
    gas: any[];
};

interface Params {
    contactos: any[];
    clientes: Cliente[];
    comercializadoras: any[];
    productos: any[];
    anexos: any[];
    cupsElectricos: any[];
    cupsGas: any[];
    localidades: Localidad[];
    bulkLoadProgressElectrico?: BulkLoadProgressControls;
    bulkLoadProgressGas?: BulkLoadProgressControls;
}

export function useContratoMultiClienteMultiPunto(params: Params) {
    const {
        contactos,
        clientes,
        comercializadoras,
        productos,
        anexos,
        bulkLoadProgressElectrico,
        bulkLoadProgressGas,
    } = params;

    const flash = usePage().props.flash as any;

    const { data, setData, post, processing, errors, transform } = useForm<ContratoFormData>({
        razon_social: '',
        documento_fiscal: '',
        fecha_propuesta: '',
        tipo_contrato: 3,
        electrico: [],
        gas: []
    });

    const getError = (field: string): string | undefined => {
        return (errors as any)[field];
    };

    const [contactosOptions, setContactosOptions] = useState<any[]>([]);
    const [selectedContacto, setSelectedContacto] = useState<any[]>([]);
    const [isLoading, setIsLoading] = useState(false);
    const { showLoading, hideLoading } = useLoading();

    const [isDatosComunes, setIsDatosComunes] = useState(false);

    const [cupsOptionsPorFila, setCupsOptionsPorFila] = useState<{ [key: string]: CupsOption[] }>({});
    const [cupsGasOptionsPorFila, setCupsGasOptionsPorFila] = useState<{ [key: string]: CupsOption[] }>({});

    const [cupsLoadingElectricoPorFila, setCupsLoadingElectricoPorFila] = useState<Record<string, boolean>>({});
    const [cupsLoadingGasPorFila, setCupsLoadingGasPorFila] = useState<Record<string, boolean>>({});

    const [cupsElectricosByCliente, setCupsElectricosByCliente] = useState<Record<number, any[]>>({});
    const [cupsGasByCliente, setCupsGasByCliente] = useState<Record<number, any[]>>({});

    const [selectedClientesElectricoPorFila, setSelectedClientesElectricoPorFila] = useState<{ [key: string]: Cliente[] }>({});
    const [selectedClientesGasPorFila, setSelectedClientesGasPorFila] = useState<{ [key: string]: Cliente[] }>({});

    const [showModalPreciosElectrico, setShowModalPreciosElectrico] = useState<number | null>(null);
    const [showModalPreciosGas, setShowModalPreciosGas] = useState<number | null>(null);

    // Estados para filtrado de clientes por representante legal
    const [clientesOriginales, setClientesOriginales] = useState<Cliente[]>([]);
    const [clientesFiltrados, setClientesFiltrados] = useState<Cliente[]>([]);

    // Hook para carga masiva de CUPS
    const { handleBulkLoadElectrico, handleBulkLoadGas } = useBulkLoadCups();

    // Hook de validación antes de guardar - Configuración de campos obligatorios
    const { validateBeforeSave, validateAllCups, showValidationErrorDialog } = useValidateCupsBeforeSave({
        electricoRequired: [
            'clienteId',
            'comercializadora',
            'producto',
            'cups_electrico',
            'fechaInicio',
            'fechaFin',
            'tarifa',
            'tipoprecio',
        ],
        gasRequired: [
            'clienteId',
            'comercializadora',
            'producto',
            'cupsGas',
            'fechaInicio',
            'fechaFin',
            'tarifaGas',
            'tipoprecio',
        ],
        fieldLabels: {
            clienteId: 'Cliente',
            cups_electrico: 'CUPS Eléctrico',
            cupsGas: 'CUPS Gas',
            comercializadora: 'Comercializadora',
            producto: 'Producto',
            anexo: 'Anexo',
            fechaInicio: 'Fecha de Inicio',
            fechaFin: 'Fecha de Fin',
            tarifa: 'Tarifa Eléctrica',
            tarifaGas: 'Tarifa Gas',
            tipoprecio: 'Tipo de Precio',
        },
    });

    useEffect(() => {
        setContactosOptions(contactos);
        // Inicializar clientes originales
        setClientesOriginales(clientes);

        // Solo resetear clientes filtrados si no hay un contacto seleccionado
        // Esto evita que se pierda el filtro cuando ocurren actualizaciones (ej. flash messages)
        if (selectedContacto.length === 0) {
            setClientesFiltrados(clientes);
        }

        if (flash?.message) {
            Swal.fire({
                icon: flash.type || "info",
                title: flash.type === "success" ? "¡Éxito!" : "¡Atención!",
                text: flash.message,
                timer: 2000,
                showConfirmButton: false,
            });
        }
    }, [flash, contactos, clientes, selectedContacto]);

    const handleClienteChange = async (clienteId: any, tipo: any, idx: any) => {
        if (tipo === 'electrico') {
            const rowIndex = idx;
            const targetRow = data.electrico[idx];
            if (!targetRow) return;

            const rowKey = targetRow.tempId || targetRow.cupsId || `idx-${idx}`;

            const clienteIdNum = Number(clienteId);

            let cupsPorCliente: any[] = cupsElectricosByCliente[clienteIdNum] || [];
            if (!cupsPorCliente.length) {
                setCupsLoadingElectricoPorFila(prev => ({ ...prev, [rowKey]: true }));
                try {
                    const response = await getCupsElectricosByClient(clienteIdNum);
                    if (response.success && Array.isArray(response.data)) {
                        cupsPorCliente = response.data;
                        setCupsElectricosByCliente(prev => ({ ...prev, [clienteIdNum]: response.data }));
                    }
                } catch (e) {
                    cupsPorCliente = [];
                } finally {
                    setCupsLoadingElectricoPorFila(prev => ({ ...prev, [rowKey]: false }));
                }
            } else {
                // Si viene de caché, asegurar que el spinner no quede activo
                setCupsLoadingElectricoPorFila(prev => ({ ...prev, [rowKey]: false }));
            }
            const cupsUtilizadosElectrico = data.electrico
                .filter((_: any, i: number) => i !== rowIndex)
                .map((row: any) => row.cups_electrico)
                .filter((cups: any) => cups);
            const cupsUtilizadosGas = data.gas
                .map((row: any) => row.cupsGas)
                .filter((cups: any) => cups);
            const todosLosCupsUtilizados = [...cupsUtilizadosElectrico, ...cupsUtilizadosGas];
            const cupsDisponibles = cupsPorCliente.filter((cup: any) => !todosLosCupsUtilizados.includes(cup.codigoCups));
            const cupsActual = data.electrico[rowIndex]?.cups_electrico;
            if (cupsActual) {
                const cupsSeleccionado = cupsPorCliente.find((cup: any) => cup.codigoCups === cupsActual);
                if (cupsSeleccionado && !cupsDisponibles.find((cup: any) => cup.codigoCups === cupsActual)) {
                    cupsDisponibles.push(cupsSeleccionado);
                }
            }
            // Usar rowKey en lugar de rowIndex
            setCupsOptionsPorFila((prev) => ({ ...prev, [rowKey]: cupsDisponibles }));
        } else {
            const rowIndex = idx;
            const targetRow = data.gas[idx];
            if (!targetRow) return;

            const rowKey = targetRow.tempId || targetRow.cupsGasId || `idx-${idx}`;

            const clienteIdNum = Number(clienteId);

            let cupsPorCliente: any[] = cupsGasByCliente[clienteIdNum] || [];
            if (!cupsPorCliente.length) {
                setCupsLoadingGasPorFila(prev => ({ ...prev, [rowKey]: true }));
                try {
                    const response = await getCupsGasByClient(clienteIdNum);
                    if (response.success && Array.isArray(response.data)) {
                        cupsPorCliente = response.data;
                        setCupsGasByCliente(prev => ({ ...prev, [clienteIdNum]: response.data }));
                    }
                } catch (e) {
                    cupsPorCliente = [];
                } finally {
                    setCupsLoadingGasPorFila(prev => ({ ...prev, [rowKey]: false }));
                }
            } else {
                // Si viene de caché, asegurar que el spinner no quede activo
                setCupsLoadingGasPorFila(prev => ({ ...prev, [rowKey]: false }));
            }
            const cupsUtilizadosElectrico = data.electrico.map((row: any) => row.cups_electrico).filter((cups: any) => cups);
            const cupsUtilizadosGas = data.gas
                .filter((_: any, i: number) => i !== rowIndex)
                .map((row: any) => row.cupsGas)
                .filter((cups: any) => cups);
            const todosLosCupsUtilizados = [...cupsUtilizadosElectrico, ...cupsUtilizadosGas];
            const cupsDisponibles = cupsPorCliente.filter((cup: any) => !todosLosCupsUtilizados.includes(cup.codigoCups));
            const cupsActual = data.gas[rowIndex]?.cupsGas;
            if (cupsActual) {
                const cupsSeleccionado = cupsPorCliente.find((cup: any) => cup.codigoCups === cupsActual);
                if (cupsSeleccionado && !cupsDisponibles.find((cup: any) => cup.codigoCups === cupsActual)) {
                    cupsDisponibles.push(cupsSeleccionado);
                }
            }
            // Usar rowKey en lugar de rowIndex
            setCupsGasOptionsPorFila((prev) => ({ ...prev, [rowKey]: cupsDisponibles }));
        }
    };

    const isFormValid = () => {
        return data.documento_fiscal !== '' && data.razon_social !== '' && data.fecha_propuesta !== '' && (data.electrico.length > 0 || data.gas.length > 0);
    };

    const handleCupsTableChange = (cups: any, idx: any) => {
        if (!cups) return;
        const updated = [...data.electrico];
        // Buscar por cupsId para evitar problemas con índices dinámicos
        const targetRow = updated[idx];
        let rowIndex = idx;
        if (targetRow && targetRow.cupsId) {
            const foundIndex = updated.findIndex((row: any) => row.cupsId === targetRow.cupsId);
            if (foundIndex >= 0) {
                rowIndex = foundIndex;
            }
        }

        const datosExistentes = {
            clienteId: updated[rowIndex].clienteId ?? '',
            documento_fiscal: updated[rowIndex].documento_fiscal || '',
            razon_social: updated[rowIndex].razon_social || '',
            comercializadora: updated[rowIndex].comercializadora || '',
            producto: updated[rowIndex].producto || '',
            anexo: updated[rowIndex].anexo || '',
            fechaInicio: updated[rowIndex].fechaInicio || '',
            fechaFin: updated[rowIndex].fechaFin || '',
            comentarios: updated[rowIndex].comentarios || '',
            potencia1: updated[rowIndex].potencia1 || '',
            potencia2: updated[rowIndex].potencia2 || '',
            potencia3: updated[rowIndex].potencia3 || '',
            potencia4: updated[rowIndex].potencia4 || '',
            potencia5: updated[rowIndex].potencia5 || '',
            potencia6: updated[rowIndex].potencia6 || '',
        } as any;

        const commonUpdates = {
            ...datosExistentes,
            cupsId: cups.cupsId,
            cups_electrico: cups.codigoCups,
            direccion: cups.direccion,
            nombreTarifa: cups.nombreTarifa,
            consumo_kw: cups.ConAnuCup,
            tarifa: cups.tarifa,
            EscPunSum: cups.EscPunSum || '',
            PlaPunSum: cups.PlaPunSum || '',
            PuePunSum: cups.PuePunSum || '',
            codigo_postal: cups.CPLocSoc || '',
            potencia1: cups.PotConP1 || '',
            potencia2: cups.PotConP2 || '',
            potencia3: cups.PotConP3 || '',
            potencia4: cups.PotConP4 || '',
            potencia5: cups.PotConP5 || '',
            potencia6: cups.PotConP6 || '',
            subtarifa: cups.subtarifa || updated[rowIndex].subtarifa || '',
        };

        if (cups.DesLoc || cups.DesPro) {
             updated[rowIndex] = { 
                ...updated[rowIndex], 
                ...commonUpdates,
                localidad: cups.localidad || null, 
                provincia: cups.provincia || null,
                DesLoc: cups.DesLoc || '',
                DesPro: cups.DesPro || ''
            } as any;
        } else if (cups.CPLocSoc) {
            const localidad = params.localidades.find(loc => loc.CPLoc === cups.CPLocSoc);
            if (localidad) {
                updated[rowIndex] = { 
                    ...updated[rowIndex], 
                    ...commonUpdates,
                    localidad: localidad.CodLoc, 
                    provincia: localidad.provincia?.CodPro || null, 
                    DesLoc: localidad.DesLoc, 
                    DesPro: localidad.provincia?.DesPro 
                } as any;
            } else {
                 updated[rowIndex] = { 
                    ...updated[rowIndex], 
                    ...commonUpdates
                } as any;
            }
        } else {
            updated[rowIndex] = { 
                ...updated[rowIndex], 
                ...commonUpdates
            } as any;
        }
        setData('electrico', updated);
    };

    const handleCupsGasTableChange = (cups: any, idx: any) => {
        if (!cups) return;
        const updated = [...data.gas];
        // Buscar por cupsGasId para evitar problemas con índices dinámicos
        const targetRow = updated[idx];
        let rowIndex = idx;
        if (targetRow && targetRow.cupsGasId) {
            const foundIndex = updated.findIndex((row: any) => row.cupsGasId === targetRow.cupsGasId);
            if (foundIndex >= 0) {
                rowIndex = foundIndex;
            }
        }

        const datosExistentes = {
            clienteId: updated[rowIndex].clienteId ?? '',
            documento_fiscal: updated[rowIndex].documento_fiscal || '',
            razon_social: updated[rowIndex].razon_social || '',
            comercializadora: updated[rowIndex].comercializadora || '',
            producto: updated[rowIndex].producto || '',
            anexo: updated[rowIndex].anexo || '',
            fechaInicio: updated[rowIndex].fechaInicio || '',
            fechaFin: updated[rowIndex].fechaFin || '',
            comentarioGas: updated[rowIndex].comentarioGas || '',
        } as any;

        const commonUpdates = {
            ...datosExistentes,
            cupsGasId: cups.cupsGasId,
            cupsGas: cups.codigoCups,
            direccionGas: cups.direccion,
            nombreTarifa: cups.nombreTarifa,
            consumoGas: cups.ConAnuCup,
            tarifaGas: cups.tarifa,
            EscPunSum: cups.EscPunSum || '',
            PlaPunSum: cups.PlaPunSum || '',
            PuePunSum: cups.PuePunSum || '',
            codigo_postal: cups.CPLocSoc || '',
            subtarifa: cups.subtarifa || updated[rowIndex].subtarifa || '',
        };

         if (cups.DesLoc || cups.DesPro) {
             updated[rowIndex] = { 
                ...updated[rowIndex], 
                ...commonUpdates,
                localidadGas: cups.localidad || '',
                provinciaGas: cups.provincia || '',
                DesLoc: cups.DesLoc || '',
                DesPro: cups.DesPro || ''
            } as any;
        } else if (cups.CPLocSoc) {
             const localidad = params.localidades.find(loc => loc.CPLoc === cups.CPLocSoc);
            if (localidad) {
                updated[rowIndex] = { 
                    ...updated[rowIndex], 
                    ...commonUpdates,
                    localidadGas: localidad.DesLoc,
                    provinciaGas: localidad.provincia?.DesPro,
                    DesLoc: localidad.DesLoc,
                    DesPro: localidad.provincia?.DesPro
                } as any;
            } else {
                 updated[rowIndex] = { 
                    ...updated[rowIndex], 
                    ...commonUpdates
                } as any;
            }
        } else {
             updated[rowIndex] = { 
                ...updated[rowIndex], 
                ...commonUpdates
            } as any;
        }
        setData('gas', updated);
    };

    const handleAddCupsElectrico = () => {
        let newElectricoRow = {
            ...initialFormDataElectrico,
            tempId: `temp-${Date.now()}-${Math.floor(Math.random() * 1000)}`,
            cupsId: '',
            documento_fiscal: '',
            razon_social: '',
            cups_electrico: '',
            direccion: '',
            nombreTarifa: '',
            consumo_kw: '',
            comercializadora: '',
            producto: '',
            anexo: '',
            fechaInicio: '',
            fechaFin: '',
            comentarios: '',
            corpoGo: '',
            tipoprecio: '',
            Id_Tarifa_Automatica: '',
            subtarifa: '',
        } as any;

        if (isDatosComunes && data.electrico.length > 0) {
            const previousRow = data.electrico[0];
            newElectricoRow = {
                ...newElectricoRow,
                comercializadora: previousRow.comercializadora,
                producto: previousRow.producto,
                codigoServicioProducto: previousRow.codigoServicioProducto,
                productoNombre: previousRow.productoNombre,
                anexo: previousRow.anexo,
                anexoNombre: previousRow.anexoNombre,
                subtarifa: previousRow.subtarifa,
                fechaInicio: previousRow.fechaInicio,
                fechaFin: previousRow.fechaFin,
                tipoprecio: previousRow.tipoprecio,
                corpoGo: previousRow.corpoGo,
                GDO: previousRow.GDO,
                Id_Tarifa_Automatica: previousRow.Id_Tarifa_Automatica,
            };
        }

        setData("electrico", [newElectricoRow, ...data.electrico]);
    };

    const handleAddCupsGas = () => {
        let newGasRow = {
            ...initialFormDataGas,
            tempId: `temp-${Date.now()}-${Math.floor(Math.random() * 1000)}`,
            cupsGasId: '',
            documento_fiscal: '',
            razon_social: '',
            cupsGas: '',
            direccionGas: '',
            nombreTarifa: '',
            consumoGas: '',
            comercializadora: '',
            producto: '',
            anexo: '',
            fechaInicio: '',
            fechaFin: '',
            comentarioGas: '',
            corpoGo: '',
            tipoprecio: '',
            Id_Tarifa_Automatica: '',
            subtarifa: '',
        } as any;

        if (isDatosComunes && data.gas.length > 0) {
            const previousRow = data.gas[0];
            newGasRow = {
                ...newGasRow,
                comercializadora: previousRow.comercializadora,
                producto: previousRow.producto,
                codigoServicioProducto: previousRow.codigoServicioProducto,
                productoNombre: previousRow.productoNombre,
                anexo: previousRow.anexo,
                anexoNombre: previousRow.anexoNombre,
                subtarifa: previousRow.subtarifa,
                fechaInicio: previousRow.fechaInicio,
                fechaFin: previousRow.fechaFin,
                tipoprecio: previousRow.tipoprecio,
                corpoGo: previousRow.corpoGo,
                GDO: previousRow.GDO,
                Id_Tarifa_Automatica: previousRow.Id_Tarifa_Automatica,
            };
        }

        setData("gas", [newGasRow, ...data.gas]);
    };

    const handleProductoTableChange = (event: React.ChangeEvent<HTMLSelectElement>, idx: number) => {
        const nuevoProducto = event.target.value;
        const seleccionado = productos.find((registro: any) => registro.CodPro == nuevoProducto);
        let updatedElectrico = [...data.electrico];

        if (isDatosComunes) {
            updatedElectrico = updatedElectrico.map((row: any) => ({
                ...row,
                producto: nuevoProducto,
                codigoServicioProducto: seleccionado ? seleccionado.CodigoServicio : '',
                productoNombre: seleccionado ? seleccionado.DesPro : '',
                anexo: '',
                anexoNombre: ''
            }));
        } else {
            // Buscar por cupsId para evitar problemas con índices dinámicos
            let rowIndex = idx;
            const targetRow = updatedElectrico[idx];
            if (targetRow && targetRow.cupsId) {
                const foundIndex = updatedElectrico.findIndex((row: any) => row.cupsId === targetRow.cupsId);
                if (foundIndex >= 0) {
                    rowIndex = foundIndex;
                }
            }

            if (seleccionado) {
                updatedElectrico[rowIndex] = { ...updatedElectrico[rowIndex], producto: nuevoProducto, codigoServicioProducto: seleccionado.CodigoServicio, productoNombre: seleccionado.DesPro, anexo: '', anexoNombre: '' };
            } else {
                updatedElectrico[rowIndex] = { ...updatedElectrico[rowIndex], producto: '', codigoServicioProducto: '', productoNombre: '', anexo: '', anexoNombre: '' };
            }
        }
        setData("electrico", updatedElectrico);
    };

    const handleAnexoTableChange = (event: React.ChangeEvent<HTMLSelectElement>, idx: number) => {
        const selectedValue = event.target.value;
        const selectedIndex = event.target.selectedIndex;
        const selectedText = selectedIndex !== -1 ? (event.target.options[selectedIndex] as any).text : '';
        let updatedElectrico = [...data.electrico];

        if (isDatosComunes) {
            updatedElectrico = updatedElectrico.map((row: any) => ({ ...row, anexo: selectedValue, anexoNombre: selectedText, subtarifa: selectedText }));
        } else {
            // Buscar por cupsId para evitar problemas con índices dinámicos
            let rowIndex = idx;
            const targetRow = updatedElectrico[idx];
            if (targetRow && targetRow.cupsId) {
                const foundIndex = updatedElectrico.findIndex((row: any) => row.cupsId === targetRow.cupsId);
                if (foundIndex >= 0) {
                    rowIndex = foundIndex;
                }
            }

            updatedElectrico[rowIndex] = { ...updatedElectrico[rowIndex], anexo: selectedValue, anexoNombre: selectedText, subtarifa: selectedText };
        }
        setData("electrico", updatedElectrico);
    };

    const handleProductoGasTableChange = (event: React.ChangeEvent<HTMLSelectElement>, idx: number) => {
        const nuevoProducto = event.target.value;
        const seleccionado = productos.find((registro: any) => registro.CodPro == nuevoProducto);
        let updatedGas = [...data.gas];

        if (isDatosComunes) {
            updatedGas = updatedGas.map((row: any) => ({
                ...row,
                producto: nuevoProducto,
                codigoServicioProducto: seleccionado ? seleccionado.CodigoServicio : '',
                productoNombre: seleccionado ? seleccionado.DesPro : '',
                anexo: '',
                anexoNombre: ''
            }));
        } else {
            // Buscar por cupsGasId para evitar problemas con índices dinámicos
            let rowIndex = idx;
            const targetRow = updatedGas[idx];
            if (targetRow && targetRow.cupsGasId) {
                const foundIndex = updatedGas.findIndex((row: any) => row.cupsGasId === targetRow.cupsGasId);
                if (foundIndex >= 0) {
                    rowIndex = foundIndex;
                }
            }

            if (seleccionado) {
                updatedGas[rowIndex] = { ...updatedGas[rowIndex], producto: nuevoProducto, codigoServicioProducto: seleccionado.CodigoServicio, productoNombre: seleccionado.DesPro, anexo: '', anexoNombre: '' };
            } else {
                updatedGas[rowIndex] = { ...updatedGas[rowIndex], producto: '', codigoServicioProducto: '', productoNombre: '', anexo: '', anexoNombre: '' };
            }
        }
        setData("gas", updatedGas);
    };

    const handleAnexoGasTableChange = (event: React.ChangeEvent<HTMLSelectElement>, idx: number) => {
        const selectedValue = event.target.value;
        const selectedIndex = event.target.selectedIndex;
        const selectedText = selectedIndex !== -1 ? (event.target.options[selectedIndex] as any).text : '';
        let updatedGas = [...data.gas];

        if (isDatosComunes) {
            updatedGas = updatedGas.map((row: any) => ({ ...row, anexo: selectedValue, anexoNombre: selectedText, subtarifa: selectedText }));
        } else {
            // Buscar por cupsGasId para evitar problemas con índices dinámicos
            let rowIndex = idx;
            const targetRow = updatedGas[idx];
            if (targetRow && targetRow.cupsGasId) {
                const foundIndex = updatedGas.findIndex((row: any) => row.cupsGasId === targetRow.cupsGasId);
                if (foundIndex >= 0) {
                    rowIndex = foundIndex;
                }
            }

            updatedGas[rowIndex] = { ...updatedGas[rowIndex], anexo: selectedValue, anexoNombre: selectedText, subtarifa: selectedText };
        }
        setData("gas", updatedGas);
    };

    const handleChangeElectrico = (formData: FormDataElectrico) => {
        // Esta función podría eliminarse si ya no se usa el modal, 
        // pero se mantiene por si se reutiliza lógica de actualización masiva
        // Actualmente la edición es en línea en la tabla
    };

    const handleChangeGas = (formData: FormDataGas) => {
        // Similar al eléctrico, la edición es en línea
    };
    
    const handleDeleteElectricoRow = (idx: number) => {
        const row = data.electrico[idx];
        const rowKey = row.tempId || row.cupsId || `idx-${idx}`;

        const updatedElectrico = data.electrico.filter((_: any, i: number) => i !== idx);
        setData("electrico", updatedElectrico);

        setSelectedClientesElectricoPorFila(prev => {
            const newState = { ...prev };
            delete newState[rowKey as any];
            return newState;
        });
        setCupsOptionsPorFila(prev => {
            const newState = { ...prev };
            delete newState[rowKey as any];
            return newState;
        });
    };

    const handleDeleteGasRow = (idx: number) => {
        const row = data.gas[idx];
        const rowKey = row.tempId || row.cupsGasId || `idx-${idx}`;

        const updatedGas = data.gas.filter((_: any, i: number) => i !== idx);
        setData("gas", updatedGas);

        setSelectedClientesGasPorFila(prev => {
            const newState = { ...prev };
            delete newState[rowKey as any];
            return newState;
        });
        setCupsGasOptionsPorFila(prev => {
            const newState = { ...prev };
            delete newState[rowKey as any];
            return newState;
        });
    };
    
    const handleClearClienteElectrico = (idx: number) => {
        const updatedElectrico = [...data.electrico];
        const row = updatedElectrico[idx];
        const rowKey = row.tempId || row.cupsId || `idx-${idx}`; // Fallback temporal

        updatedElectrico[idx] = {
            ...updatedElectrico[idx],
            documento_fiscal: '',
            razon_social: '',
            cups_electrico: '',
            direccion: '',
            nombreTarifa: '',
            consumo_kw: '',
            clienteId: '' // Limpiar clienteId
        } as any;
        setData("electrico", updatedElectrico);

        // Limpiar estados auxiliares usando rowKey
        setSelectedClientesElectricoPorFila(prev => {
            const newState = { ...prev };
            delete newState[rowKey as any]; // Usar delete es más limpio
            return newState;
        });
        setCupsOptionsPorFila(prev => {
            const newState = { ...prev };
            delete newState[rowKey as any];
            return newState;
        });
    };

    const handleClearClienteGas = (idx: number) => {
        const updatedGas = [...data.gas];
        const row = updatedGas[idx];
        const rowKey = row.tempId || row.cupsGasId || `idx-${idx}`;

        updatedGas[idx] = {
            ...updatedGas[idx],
            documento_fiscal: '',
            razon_social: '',
            cupsGas: '',
            direccionGas: '',
            nombreTarifa: '',
            consumoGas: '',
            clienteId: '' // Limpiar clienteId
        } as any;
        setData("gas", updatedGas);

        setSelectedClientesGasPorFila(prev => {
            const newState = { ...prev };
            delete newState[rowKey as any];
            return newState;
        });
        setCupsGasOptionsPorFila(prev => {
            const newState = { ...prev };
            delete newState[rowKey as any];
            return newState;
        });
    };

    const handleClearCupsElectrico = (idx: number) => {
        const updatedElectrico = [...data.electrico];
        const clienteData = {
            clienteId: updatedElectrico[idx].clienteId ?? '',
            documento_fiscal: updatedElectrico[idx].documento_fiscal || '',
            razon_social: updatedElectrico[idx].razon_social || ''
        } as any;
        updatedElectrico[idx] = { ...updatedElectrico[idx], ...clienteData, cupsId: '', cups_electrico: '', direccion: '', nombreTarifa: '', consumo_kw: '', tarifa: '', EscPunSum: '', PlaPunSum: '', PuePunSum: '', codigo_postal: '', localidad: null, provincia: null } as any;
        setData("electrico", updatedElectrico);
    };

    const handleClearCupsGas = (idx: number) => {
        const updatedGas = [...data.gas];
        const clienteData = {
            clienteId: updatedGas[idx].clienteId ?? '',
            documento_fiscal: updatedGas[idx].documento_fiscal || '',
            razon_social: updatedGas[idx].razon_social || ''
        } as any;
        updatedGas[idx] = { ...updatedGas[idx], ...clienteData, cupsGasId: '', cupsGas: '', direccionGas: '', nombreTarifa: '', consumoGas: '', tarifaGas: '', EscPunSum: '', PlaPunSum: '', PuePunSum: '', codigo_postal: '', localidadGas: '', provinciaGas: '' } as any;
        setData("gas", updatedGas);
    };
    
    const handleDatosComunes = () => {
        setIsDatosComunes(prev => !prev);
    };

    const handleElectricoFieldChange = (idx: number, field: string, value: string) => {
        let updatedElectrico = [...data.electrico];
        // Buscar por cupsId para evitar problemas con índices dinámicos
        const targetRow = updatedElectrico[idx];
        let rowIndex = idx;
        if (targetRow && targetRow.cupsId) {
            const foundIndex = updatedElectrico.findIndex((row: any) => row.cupsId === targetRow.cupsId);
            if (foundIndex >= 0) {
                rowIndex = foundIndex;
            }
        }

        if (isDatosComunes && ['comercializadora', 'producto', 'anexo','fechaInicio','fechaFin', 'tipoprecio','corpoGo', 'GDO'].includes(field)) {
            updatedElectrico = updatedElectrico.map((row: any) => ({
                ...row,
                [field]: value,
                ...(field === 'comercializadora' ? { producto: '', productoNombre: '', codigoServicioProducto: '', anexo: '', anexoNombre: '', fechaInicio: '', fechaFin: '', tipoprecio: '', corpoGo: '' } : {}),
                ...(field === 'producto' ? { anexo: '', anexoNombre: '' } : {})
            }));
        } else {
            if (field === 'comercializadora') {
                updatedElectrico[rowIndex] = { ...updatedElectrico[rowIndex], [field]: value, producto: '', productoNombre: '', codigoServicioProducto: '', anexo: '', anexoNombre: '', tipoprecio: '', corpoGo: '' } as any;
            } else {
                updatedElectrico[rowIndex] = { ...updatedElectrico[rowIndex], [field]: value } as any;
            }
        }
        setData("electrico", updatedElectrico);
    };

    const handleGasFieldChange = (idx: number, field: string, value: string) => {
        let updatedGas = [...data.gas];
        // Buscar por cupsGasId para evitar problemas con índices dinámicos
        const targetRow = updatedGas[idx];
        let rowIndex = idx;
        if (targetRow && targetRow.cupsGasId) {
            const foundIndex = updatedGas.findIndex((row: any) => row.cupsGasId === targetRow.cupsGasId);
            if (foundIndex >= 0) {
                rowIndex = foundIndex;
            }
        }

        if (isDatosComunes && ['comercializadora', 'producto', 'anexo', 'fechaInicio', 'fechaFin','tipoprecio','corpoGo', 'GDO'].includes(field)) {
            updatedGas = updatedGas.map((row: any) => ({
                ...row,
                [field]: value,
                ...(field === 'comercializadora' ? { producto: '', productoNombre: '', codigoServicioProducto: '', anexo: '', anexoNombre: '', tipoprecio: '', corpoGo: '' } : {}),
                ...(field === 'producto' ? { anexo: '', anexoNombre: '' } : {})
            }));
        } else {
            if (field === 'comercializadora') {
                updatedGas[rowIndex] = { ...updatedGas[rowIndex], [field]: value, producto: '', productoNombre: '', codigoServicioProducto: '', anexo: '', anexoNombre: '', tipoprecio: '', corpoGo: '' } as any;
            } else {
                updatedGas[rowIndex] = { ...updatedGas[rowIndex], [field]: value } as any;
            }
        }
        setData("gas", updatedGas);
    };

    /**
     * Carga masiva de todos los CUPS eléctricos disponibles
     */
    const bulkLoadAllCupsElectrico = async () => {
        if (selectedContacto.length === 0) {
            Swal.fire({
                icon: 'warning',
                title: 'Representante Legal Requerido',
                text: 'Debe seleccionar un representante legal antes de cargar los CUPS',
                confirmButtonText: 'Entendido',
            });
            return;
        }

        if (clientesFiltrados.length === 0) {
            Swal.fire({
                icon: 'info',
                title: 'Sin Clientes Disponibles',
                text: 'No hay clientes asociados a este representante legal',
                confirmButtonText: 'Entendido',
            });
            return;
        }

        const cupsUtilizados = [
            ...data.electrico.map((row: any) => row.cups_electrico),
            ...data.gas.map((row: any) => row.cupsGas),
        ].filter(Boolean);

        const datosComunes = isDatosComunes && data.electrico.length > 0
            ? data.electrico[0]
            : undefined;

        const clienteIds = clientesFiltrados
            .map((c: any) => Number(c.CodCli))
            .filter((id: number) => Number.isFinite(id) && id > 0);

        bulkLoadProgressElectrico?.start('Preparando carga masiva eléctrica...');

        let cupsForClientes: any[] = [];

        if (clienteIds.length) {
            try {
                bulkLoadProgressElectrico?.setPercent(10, 'Obteniendo CUPS del servidor...');
                const response = await getCupsElectricosByClientes(clienteIds);

                if (response.success && Array.isArray(response.data)) {
                    cupsForClientes = response.data;

                    const grouped = response.data.reduce((acc: any, item: any) => {
                        const id = Number(item.CodCli);
                        if (!Number.isFinite(id) || id <= 0) {
                            return acc;
                        }

                        (acc[id] = acc[id] || []).push(item);
                        return acc;
                    }, {} as Record<number, any[]>);

                    setCupsElectricosByCliente((prev) => ({ ...prev, ...grouped }));
                } else {
                    bulkLoadProgressElectrico?.fail('No se pudieron obtener los CUPS eléctricos');
                    return;
                }
            } catch {
                bulkLoadProgressElectrico?.fail('Error al obtener los CUPS eléctricos del servidor');
                return;
            }
        }

        bulkLoadProgressElectrico?.setPercent(20, 'Procesando filas de la tabla...');

        let newRows: any[] = [];

        try {
            newRows = await handleBulkLoadElectrico(
                clientesFiltrados,
                cupsForClientes,
                cupsUtilizados,
                isDatosComunes,
                datosComunes,
                bulkLoadProgressElectrico,
            );
        } catch {
            return;
        }

        if (newRows.length === 0) {
            bulkLoadProgressElectrico?.complete('No hay CUPS eléctricos nuevos para cargar');
            Swal.fire({
                icon: 'info',
                title: 'Sin CUPS Disponibles',
                text: 'No hay CUPS eléctricos disponibles para cargar. Todos los CUPS ya están en uso o no hay CUPS asociados a estos clientes.',
                confirmButtonText: 'Entendido',
            });
            return;
        }

        setData('electrico', [...data.electrico, ...newRows]);
        bulkLoadProgressElectrico?.complete(`Se cargaron ${newRows.length} CUPS eléctricos`);

        Swal.fire({
            icon: 'success',
            title: '¡CUPS Cargados!',
            text: `Se han cargado ${newRows.length} CUPS eléctricos exitosamente`,
            timer: 2000,
            showConfirmButton: false,
        });
    };

    /**
     * Carga masiva de todos los CUPS gas disponibles
     */
    const bulkLoadAllCupsGas = async () => {
        // Validación 1: Verificar que hay un representante legal seleccionado
        if (selectedContacto.length === 0) {
            Swal.fire({
                icon: 'warning',
                title: 'Representante Legal Requerido',
                text: 'Debe seleccionar un representante legal antes de cargar los CUPS',
                confirmButtonText: 'Entendido'
            });
            return;
        }

        // Validación 2: Verificar que hay clientes filtrados
        if (clientesFiltrados.length === 0) {
            Swal.fire({
                icon: 'info',
                title: 'Sin Clientes Disponibles',
                text: 'No hay clientes asociados a este representante legal',
                confirmButtonText: 'Entendido'
            });
            return;
        }

        // Obtener CUPS ya utilizados
        const cupsUtilizados = [
            ...data.electrico.map((row: any) => row.cups_electrico),
            ...data.gas.map((row: any) => row.cupsGas)
        ].filter(Boolean);

        // Obtener datos comunes si está activo
        const datosComunes = isDatosComunes && data.gas.length > 0
            ? data.gas[0]
            : undefined;

        const clienteIds = clientesFiltrados
            .map((c: any) => Number(c.CodCli))
            .filter((id: number) => Number.isFinite(id) && id > 0);

        bulkLoadProgressGas?.start('Preparando carga masiva de gas...');

        let cupsForClientes: any[] = [];
        if (clienteIds.length) {
            try {
                bulkLoadProgressGas?.setPercent(10, 'Obteniendo CUPS del servidor...');
                const response = await getCupsGasByClientes(clienteIds);
                if (response.success && Array.isArray(response.data)) {
                    cupsForClientes = response.data;

                    const grouped = response.data.reduce((acc: any, item: any) => {
                        const id = Number(item.CodCli);
                        if (!Number.isFinite(id) || id <= 0) return acc;
                        (acc[id] = acc[id] || []).push(item);
                        return acc;
                    }, {} as Record<number, any[]>);

                    setCupsGasByCliente(prev => ({ ...prev, ...grouped }));
                } else {
                    bulkLoadProgressGas?.fail('No se pudieron obtener los CUPS de gas');
                    return;
                }
            } catch (e) {
                bulkLoadProgressGas?.fail('Error al obtener los CUPS de gas del servidor');
                return;
            }
        }

        bulkLoadProgressGas?.setPercent(20, 'Procesando filas de la tabla...');

        let newRows: any[] = [];
        try {
            newRows = await handleBulkLoadGas(
                clientesFiltrados,
                cupsForClientes,
                cupsUtilizados,
                isDatosComunes,
                datosComunes,
                bulkLoadProgressGas,
            );
        } catch {
            return;
        }

        if (newRows.length === 0) {
            bulkLoadProgressGas?.complete('No hay CUPS de gas nuevos para cargar');
            Swal.fire({
                icon: 'info',
                title: 'Sin CUPS Disponibles',
                text: 'No hay CUPS de Gas disponibles para cargar. Todos los CUPS ya están en uso o no hay CUPS asociados a estos clientes.',
                confirmButtonText: 'Entendido'
            });
            return;
        }

        setData('gas', [...data.gas, ...newRows]);
        bulkLoadProgressGas?.complete(`Se cargaron ${newRows.length} CUPS de gas`);

        // Mostrar confirmación
        Swal.fire({
            icon: 'success',
            title: '¡CUPS Cargados!',
            text: `Se han cargado ${newRows.length} CUPS de Gas exitosamente`,
            timer: 2000,
            showConfirmButton: false
        });
    }

    const saveContrato = async (e: React.FormEvent) => {
        e.preventDefault();
        
        post(route('contratos.save-contrato-multi-cliente-multi-punto'), {
            onSuccess: () => {
                Swal.fire({
                    icon: 'success',
                    title: '¡Éxito!',
                    text: 'Contrato guardado correctamente',
                    timer: 2000,
                    showConfirmButton: false
                });
                router.visit(route("contratos.index"));
            },
            onError: (errors) => {
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: 'Por favor revise los errores en el formulario',
                    confirmButtonText: 'Entendido'
                });
            }
        });
    };

    const handleClearAll = () => {
        Swal.fire({
            title: '¿Limpiar todo?',
            text: "Se borrarán todos los datos del formulario. Esta acción no se puede deshacer.",
            icon: 'warning',
            showCancelButton: true,
            focusCancel: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Sí, limpiar',
            cancelButtonText: 'Cancelar'
        }).then((result) => {
            if (result.isConfirmed) {
                setData({
                    razon_social: '',
                    documento_fiscal: '',
                    fecha_propuesta: '',
                    tipo_contrato: 3,
                    electrico: [],
                    gas: []
                });

                setSelectedContacto([]);
                setIsDatosComunes(false);

                Swal.fire(
                    '¡Limpio!',
                    'El formulario ha sido restablecido correctamente.',
                    'success'
                );
            }
        });
    };

    const filterClientesByRepresentanteLegal = (contacto: Contacto | null) => {
        // 1. Validamos que el contacto recibido tenga el ID de contacto (CodConCli)
        const targetCodConCli = contacto?.CodConCli;
    
        if (targetCodConCli) {
            const filtered = clientesOriginales.filter(cliente => {
                /**
                 * Dado que 'contacto_detalle_cliente' es un ARRAY, usamos .some()
                 * para buscar en la jerarquía: detalle -> contacto -> CodConCli
                 */
                return cliente.contacto_detalle_cliente?.some(detalle => {
                    // Comparamos el CodConCli del objeto contacto interno con el recibido por parámetro
                    return Number(detalle.contacto?.CodConCli) === Number(targetCodConCli);
                });
            });
    
            setClientesFiltrados(filtered);
        } else {
            // Si no hay un contacto seleccionado o no tiene ID, restauramos la lista original
            setClientesFiltrados(clientesOriginales);
        }
    };

    return {
        data,
        setData,
        post,
        processing,
        errors,
        handleClienteChange,
        handleCupsTableChange,
        handleCupsGasTableChange,
        handleAddCupsElectrico,
        handleAddCupsGas,
        handleProductoTableChange,
        handleAnexoTableChange,
        handleProductoGasTableChange,
        handleAnexoGasTableChange,
        handleChangeElectrico,
        handleChangeGas,
        handleDeleteElectricoRow,
        handleDeleteGasRow,
        handleClearClienteElectrico,
        handleClearClienteGas,
        handleClearCupsElectrico,
        handleClearCupsGas,
        handleDatosComunes,
        handleElectricoFieldChange,
        handleGasFieldChange,
        isDatosComunes,
        cupsOptionsPorFila,
        cupsGasOptionsPorFila,
        cupsLoadingElectricoPorFila,
        cupsLoadingGasPorFila,
        handleBulkLoadElectrico,
        handleBulkLoadGas,
        validateBeforeSave,
        validateAllCups,
        showValidationErrorDialog,
        getError,
        selectedClientesElectricoPorFila,
        setSelectedClientesElectricoPorFila,
        selectedClientesGasPorFila,
        setSelectedClientesGasPorFila,
        contactosOptions,
        setContactosOptions,
        setSelectedContacto,
        selectedContacto,
        isLoading,
        showLoading,
        hideLoading,
        setIsLoading,
        setShowModalPreciosElectrico,
        showModalPreciosElectrico,
        setShowModalPreciosGas,
        showModalPreciosGas,
        filterClientesByRepresentanteLegal,
        clientesFiltrados,
        saveContrato,
        bulkLoadAllCupsElectrico,
        bulkLoadAllCupsGas,
        isFormValid,
        handleClearAll
    };
}
