import { useState } from 'react';
import { FormDataGas, Localidad } from '../../Interfaces/Interfaces';
import { initialFormDataGas } from '../../Interfaces/constants';
import { calcularFechaFinContratoDesdeInicio } from '../../utils/fechaContratoUtils';

interface UseCupsGasManagementProps {
    dataGas: FormDataGas[];
    setData: (key: string, value: any) => void;
    localidades: Localidad[];
    productos: any[];
    actualizarOpcionesCupsPorFila: () => void;
    isDatosComunes?: boolean;
}

export const useCupsGasManagement = ({
    dataGas,
    setData,
    localidades,
    productos,
    actualizarOpcionesCupsPorFila,
    isDatosComunes = false
}: UseCupsGasManagementProps) => {
    const [formDataGas, setFormDataGas] = useState<FormDataGas>({} as FormDataGas);
    const [isModalOpenGas, setIsModalOpenGas] = useState(false);
    const [index, setIndex] = useState(-1);

    const handleShowCupsGasModal = () => {
        let newGasRow = {
            ...initialFormDataGas,
            cupsGasId: `temp_gas_${Date.now()}`,
            tempId: `row_gas_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
        };

        // Si hay datos comunes activos y existe al menos un CUPS gas, heredar datos del último
        if (isDatosComunes && dataGas.length > 0) {
            const lastRow = dataGas[0]; // El último insertado está en la posición 0
            newGasRow = {
                ...newGasRow,
                comercializadora: lastRow.comercializadora || '',
                comercializadoraNombre: lastRow.comercializadoraNombre || '',
                codigoServicioProducto: lastRow.codigoServicioProducto || '',
                producto: lastRow.producto || '',
                productoNombre: lastRow.productoNombre || '',
                anexo: lastRow.anexo || '',
                anexoNombre: lastRow.anexoNombre || '',
                fechaInicio: lastRow.fechaInicio || '',
                fechaFin: lastRow.fechaFin || '',
                tipoprecio: lastRow.tipoprecio || '',
                corpoGo: lastRow.corpoGo || '',
                GDO: lastRow.GDO || '',
                Id_Tarifa_Automatica: lastRow.Id_Tarifa_Automatica || '',
            };
        }

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

    const handleCloseGasCupsModal = () => {
        setIsModalOpenGas(false);
        setFormDataGas({} as FormDataGas);
        setIndex(-1);
    };

    const handleEditGas = (editIndex: number) => {
        handleOpenEditGasCupsModal(editIndex);
    };

    const handleOpenEditGasCupsModal = (editIndex: number) => {
        setIndex(editIndex);
        const registro = dataGas[editIndex];

        const formDataCompleto = {
            ...initialFormDataGas,
            ...registro,
            cupsGasId: registro.cupsGasId || '',
            cupsGas: registro.cupsGas || '',
            direccionGas: registro.direccionGas || '',
            EscPunSum: registro.EscPunSum || '',
            PlaPunSum: registro.PlaPunSum || '',
            PuePunSum: registro.PuePunSum || '',
            localidadGas: registro.localidadGas || '',
            provinciaGas: registro.provinciaGas || '',
            codigo_postal: registro.codigo_postal || '',
            tarifaGas: registro.tarifaGas || '',
            nombreTarifa: registro.nombreTarifa || '',
            corpoGo: registro.corpoGo || '',
            Id_Tarifa_Automatica: registro.Id_Tarifa_Automatica || '',
            consumoGas: registro.consumoGas || '',
            caudal_diario: registro.caudal_diario || '',
            comercializadora: registro.comercializadora || '',
            comercializadoraNombre: registro.comercializadoraNombre || '',
            codigoServicioProducto: registro.codigoServicioProducto || '',
            producto: registro.producto || '',
            productoNombre: registro.productoNombre || '',
            anexo: registro.anexo || '',
            anexoNombre: registro.anexoNombre || '',
            fechaInicio: registro.fechaInicio || '',
            fechaFin: registro.fechaFin || '',
            tipoprecio: registro.tipoprecio || '',
            comentarioGas: registro.comentarioGas || '',
        };

        setFormDataGas(formDataCompleto);
        setIsModalOpenGas(true);
    };

    const handleChangeGas = (formData: FormDataGas, editIndex?: number) => {
        const targetIndex = editIndex !== undefined ? editIndex : index;

        if (targetIndex >= 0 && targetIndex < dataGas.length) {
            const updatedGas = [...dataGas];
            const tempId = (updatedGas[targetIndex] as any).tempId;
            updatedGas[targetIndex] = { ...formData, ...(tempId ? { tempId } : {}) };
            setData("gas", updatedGas);
        } else {
            const existingIndex = dataGas.findIndex(item => item.cupsGasId === formData.cupsGasId);
            if (existingIndex >= 0) {
                const updatedGas = [...dataGas];
                const tempId = (updatedGas[existingIndex] as any).tempId;
                updatedGas[existingIndex] = { ...formData, ...(tempId ? { tempId } : {}) };
                setData("gas", updatedGas);
            } else {
                setData("gas", [...dataGas, { ...formData }]);
            }
        }

        setIsModalOpenGas(false);
        setIndex(-1);
    };

    const handleCupsGasTableChange = (cups: any | null, rowIndex: number) => {
        if (cups) {
            const updatedGas = [...dataGas];
            const currentRow = updatedGas[rowIndex] as any;
            const datosComerciales = {
                comercializadora: updatedGas[rowIndex].comercializadora || '',
                comercializadoraNombre: updatedGas[rowIndex].comercializadoraNombre || '',
                codigoServicioProducto: updatedGas[rowIndex].codigoServicioProducto || '',
                producto: updatedGas[rowIndex].producto || '',
                productoNombre: updatedGas[rowIndex].productoNombre || '',
                anexo: updatedGas[rowIndex].anexo || '',
                anexoNombre: updatedGas[rowIndex].anexoNombre || '',
                fechaInicio: updatedGas[rowIndex].fechaInicio || '',
                fechaFin: updatedGas[rowIndex].fechaFin || '',
                tipoprecio: updatedGas[rowIndex].tipoprecio || '',
                comentarioGas: updatedGas[rowIndex].comentarioGas || '',
            };

            updatedGas[rowIndex] = {
                ...updatedGas[rowIndex],
                ...datosComerciales,
                cupsGasId: cups.cupsGasId,
                cupsGas: cups.codigoCups,
                codigoCups: cups.codigoCups,
                direccionGas: cups.direccion,
                tarifaGas: cups.tarifa,
                nombreTarifa: cups.nombreTarifa,
                consumoGas: cups.ConAnuCup,
                localidadGas: cups.localidadGas || '',
                provinciaGas: cups.provinciaGas || '',
                EscPunSum: cups.EscPunSum || '',
                PlaPunSum: cups.PlaPunSum || '',
                PuePunSum: cups.PuePunSum || '',
                codigo_postal: cups.CPLocSoc || '',
                corpoGo: cups.corpoGo || '',
                // Preserve tempId
                ...(currentRow.tempId ? { tempId: currentRow.tempId } : {})
            };

            if (cups.CPLocSoc) {
                const localidad = localidades.find(loc => loc.CPLoc === cups.CPLocSoc);
                if (localidad) {
                    updatedGas[rowIndex] = {
                        ...updatedGas[rowIndex],
                        localidadGas: localidad.DesLoc,
                        provinciaGas: localidad.provincia?.DesPro || ''
                    };
                }
            }

            setData("gas", updatedGas);
            setTimeout(() => actualizarOpcionesCupsPorFila(), 100);
        }
    };

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

        if (isDatosComunes) {
            updatedGas = updatedGas.map((row, idx) =>
                idx === rowIndex
                    ? {
                        ...row,
                        producto: nuevoProducto,
                        codigoServicioProducto: seleccionado ? seleccionado.CodigoServicio : '',
                        productoNombre: seleccionado ? seleccionado.DesPro : '',
                        anexo: '',
                        anexoNombre: '',
                        corpoGo: ''
                    }
                    : row
            );
            setData("gas", updatedGas);
            setFormDataGas(prev => ({
                ...prev,
                producto: nuevoProducto,
                codigoServicioProducto: seleccionado ? seleccionado.CodigoServicio : '',
                productoNombre: seleccionado ? seleccionado.DesPro : '',
                anexo: '',
                anexoNombre: '',
                corpoGo: ''
            }));
        } else {
            if (seleccionado) {
                updatedGas[rowIndex] = {
                    ...updatedGas[rowIndex],
                    producto: nuevoProducto,
                    codigoServicioProducto: seleccionado.CodigoServicio,
                    productoNombre: seleccionado.DesPro,
                    anexo: '',
                    anexoNombre: '',
                    corpoGo: ''
                };
            } else {
                updatedGas[rowIndex] = {
                    ...updatedGas[rowIndex],
                    producto: '',
                    codigoServicioProducto: '',
                    productoNombre: '',
                    anexo: '',
                    anexoNombre: '',
                    corpoGo: ''
                };
            }
            setData("gas", updatedGas);
            setFormDataGas(prev => ({
                ...prev,
                producto: seleccionado ? nuevoProducto : '',
                codigoServicioProducto: seleccionado ? seleccionado.CodigoServicio : '',
                productoNombre: seleccionado ? seleccionado.DesPro : '',
                anexo: '',
                anexoNombre: '',
                corpoGo: ''
            }));
        }
    };

    const handleAnexoGasTableChange = (event: React.ChangeEvent<HTMLSelectElement>, rowIndex: number, isDatosComunes: boolean) => {
        const selectedValue = event.target.value;
        const selectedIndex = event.target.selectedIndex;
        const selectedText = selectedIndex !== -1 ? event.target.options[selectedIndex].text : '';
        let updatedGas = [...dataGas];

        if (isDatosComunes) {
            updatedGas = updatedGas.map(row => ({
                ...row,
                anexo: selectedValue,
                anexoNombre: selectedText
            }));
        } else {
            updatedGas[rowIndex] = {
                ...updatedGas[rowIndex],
                anexo: selectedValue,
                anexoNombre: selectedText,
            };
        }
        setData("gas", updatedGas);
    };

    const handleGasFieldChange = (rowIndex: number, field: string, value: string, isDatosComunes: boolean) => {
        let updatedGas = [...dataGas];

        if (field === 'fechaInicio') {
            const fechaFin = calcularFechaFinContratoDesdeInicio(value);
            if (isDatosComunes) {
                updatedGas = updatedGas.map((row) => ({
                    ...row,
                    fechaInicio: value,
                    fechaFin,
                }));
                setFormDataGas((prev) => ({ ...prev, fechaInicio: value, fechaFin }));
            } else {
                updatedGas[rowIndex] = {
                    ...updatedGas[rowIndex],
                    fechaInicio: value,
                    fechaFin,
                };
                setFormDataGas((prev) => ({ ...prev, fechaInicio: value, fechaFin }));
            }
            setData('gas', updatedGas);
            return;
        }

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

    const handleDeleteGasRow = (rowIndex: number) => {
        const updatedGas = dataGas.filter((_, i) => i !== rowIndex);
        setData("gas", updatedGas);

        if (dataGas.length <= 1) {
            setFormDataGas(prev => ({
                ...prev,
                cupsGasId: '',
                cupsGas: '',
                direccionGas: '',
                tarifaGas: '',
                corpoGo: '',
                nombreTarifa: '',
                consumoGas: '',
            }));
        }

        setTimeout(() => actualizarOpcionesCupsPorFila(), 100);
    };

    const handleClearCupsGas = (rowIndex: number) => {
        const updatedGas = [...dataGas];
        updatedGas[rowIndex] = {
            ...updatedGas[rowIndex],
            cupsGasId: '',
            cupsGas: '',
            codigoCups: '',
            direccionGas: '',
            tarifaGas: '',
            nombreTarifa: '',
            consumoGas: '',
            caudal_diario: '',
            localidadGas: '',
            provinciaGas: '',
            codigo_postal: '',
            EscPunSum: '',
            PlaPunSum: '',
            PuePunSum: '',
            corpoGo: '',
            Id_Tarifa_Automatica: ''
        };
        setData("gas", updatedGas);
        setTimeout(() => actualizarOpcionesCupsPorFila(), 100);
    };

    return {
        formDataGas,
        setFormDataGas,
        isModalOpenGas,
        setIsModalOpenGas,
        index,
        setIndex,
        handleShowCupsGasModal,
        handleCloseGasCupsModal,
        handleEditGas,
        handleOpenEditGasCupsModal,
        handleChangeGas,
        handleCupsGasTableChange,
        handleProductoGasTableChange,
        handleAnexoGasTableChange,
        handleGasFieldChange,
        handleDeleteGasRow,
        handleClearCupsGas
    };
};

