import React, { useEffect, useMemo, useState } from 'react';
import { Form } from 'react-bootstrap';
import { Typeahead } from 'react-bootstrap-typeahead';
import { Zap, Pencil, Trash2, X, Search, ChevronLeft, ChevronRight, FilterX } from 'lucide-react';
import { CupsOption, Cliente } from '../../Interfaces/Interfaces';
import ModalPrecios from '../../ModalPrecios';
import { buildVentanaRowPatch } from '../../ComponentesComunes/ventanaPreciosUtils';
import {
    ServiciosContratoTableCells,
    ServiciosContratoTableHeaders,
} from '../../ComponentesComunes/ServiciosContratoFields';
import { formatToYYYYMMDD } from '../../../Utils';
import { obtenerIdDomCeldaTabla } from '../../utils/validacionFormulario';
import { obtenerIdDomClienteFila } from '../utils/idsDomMultiClienteMultipunto';
import { TypeaheadClienteConLimpiar } from '../../Shared/TypeaheadClienteConLimpiar';
import {
    filterSelectEq,
    filterText,
    filterTriBool,
    origenRowHasTarifaParaVentana,
    rowMatchesVentanaTarifaFiltro,
} from '../../Shared/cupsTableFilterUtils';
import styles from '../css/MultiClienteMultiPunto.module.css';
import FormDateInputEs from '../../../../../Components/Common/FormDateInputEs';

const emptyMultiElectricFilters = () => ({
    documento_fiscal: '',
    razon_social: '',
    cups_electrico: '',
    direccion: '',
    nombreTarifa: '',
    consumo: '',
    comercializadora: '',
    producto: '',
    tipoprecio: '',
    GDO: '',
    anexo: '',
    permanencia: '',
    fechaInicio: '',
    fechaFin: '',
    cambioTitular: '',
    cambioPotencia: '',
    corpoGo: '',
    ventana: '',
});

interface CupsElectricosTableProps {
    data: any[];
    setData: (key: string, value: any) => void;
    clientes: Cliente[];
    selectedClientesPorFila: { [key: string]: Cliente[] };
    setSelectedClientesPorFila: React.Dispatch<React.SetStateAction<{ [key: string]: Cliente[] }>>;
    cupsOptionsPorFila: { [key: string]: CupsOption[] };
    cupsLoadingPorFila: { [key: string]: boolean };
    comercializadoras: any[];
    productos: any[];
    anexos: any[];
    tipoprecio: any[];
    isLoading: boolean;
    isDatosComunes: boolean;
    showModalPrecios: number | null;
    setShowModalPrecios: (index: number | null) => void;
    onClienteChange: (clienteId: any, tipo: string, index: number) => void;
    onCupsChange: (cups: any, index: number) => void;
    onFieldChange: (index: number, field: string, value: string) => void;
    onProductoChange: (event: React.ChangeEvent<HTMLSelectElement>, index: number) => void;
    onAnexoChange: (event: React.ChangeEvent<HTMLSelectElement>, index: number) => void;
    onClearCliente: (index: number) => void;
    onClearCups: (index: number) => void;
    onDelete: (index: number) => void;
    onEdit: (index: number) => void;
    erroresPorFila?: Record<number, Record<string, string>>;
    mostrarErrores?: boolean;
}

const FeedbackCeldaTabla: React.FC<{ id: string; mensaje?: string }> = ({ id, mensaje }) => {
    if (!mensaje) {
        return null;
    }

    return (
        <Form.Control.Feedback type="invalid" className={`d-block ${styles.feedbackCeldaTabla}`} id={id}>
            {mensaje}
        </Form.Control.Feedback>
    );
};

export const CupsElectricosTable: React.FC<CupsElectricosTableProps> = ({
    data,
    setData,
    clientes,
    selectedClientesPorFila,
    setSelectedClientesPorFila,
    cupsOptionsPorFila,
    cupsLoadingPorFila,
    comercializadoras,
    productos,
    anexos,
    tipoprecio,
    isLoading,
    isDatosComunes,
    showModalPrecios,
    setShowModalPrecios,
    onClienteChange,
    onCupsChange,
    onFieldChange,
    onProductoChange,
    onAnexoChange,
    onClearCliente,
    onClearCups,
    onDelete,
    onEdit,
    erroresPorFila = {},
    mostrarErrores = false,
}) => {
    const tableContainerRef = React.useRef<HTMLDivElement>(null);

    const scrollLeft = () => {
        if (tableContainerRef.current) {
            tableContainerRef.current.scrollBy({ left: -300, behavior: 'smooth' });
        }
    };

    const scrollRight = () => {
        if (tableContainerRef.current) {
            tableContainerRef.current.scrollBy({ left: 300, behavior: 'smooth' });
        }
    };

    const [filters, setFilters] = useState(emptyMultiElectricFilters);
    const clearFilters = () => setFilters(emptyMultiElectricFilters());

    const visibleRows = useMemo(() => {
        return data
            .map((row, originalIndex) => ({ row, originalIndex }))
            .filter(({ row }) => {
                if (!filterText(row.documento_fiscal, filters.documento_fiscal)) return false;
                if (!filterText(row.razon_social, filters.razon_social)) return false;
                if (!filterText(row.cups_electrico, filters.cups_electrico)) return false;
                if (!filterText(row.direccion, filters.direccion)) return false;
                if (!filterText(row.nombreTarifa, filters.nombreTarifa)) return false;
                const cons = row.consumo_kw ? `${row.consumo_kw} kWh` : '';
                if (!filterText(cons, filters.consumo)) return false;
                if (!filterSelectEq(row.comercializadora, filters.comercializadora)) return false;
                if (!filterSelectEq(row.producto, filters.producto)) return false;
                if (!filterSelectEq(row.tipoprecio, filters.tipoprecio)) return false;
                if (!filterTriBool(row.GDO, filters.GDO)) return false;
                if (!filterSelectEq(row.anexo, filters.anexo)) return false;
                if (!filterTriBool(row.permanencia, filters.permanencia)) return false;
                if (!filterText(row.fechaInicio, filters.fechaInicio)) return false;
                if (!filterText(row.fechaFin, filters.fechaFin)) return false;
                if (!filterTriBool(row.cambioTitular, filters.cambioTitular)) return false;
                if (!filterTriBool(row.cambioPotencia, filters.cambioPotencia)) return false;
                if (!filterText(row.corpoGo, filters.corpoGo)) return false;
                if (!filterText(row.Id_Tarifa_Automatica, filters.ventana)) return false;
                return true;
            });
    }, [data, filters]);

    useEffect(() => {
        if (!mostrarErrores) {
            return;
        }

        const indicesConError = Object.keys(erroresPorFila).map(Number);
        const algunaFilaOculta = indicesConError.some(
            (indice) => !visibleRows.some(({ originalIndex }) => originalIndex === indice),
        );

        if (algunaFilaOculta) {
            clearFilters();
        }
    }, [mostrarErrores, erroresPorFila, visibleRows]);

    const errorCampo = (index: number, campo: string): string | undefined =>
        mostrarErrores ? erroresPorFila[index]?.[campo] : undefined;

    const errorCampoCliente = (index: number, campo: string): string | undefined => {
        if (!mostrarErrores) {
            return undefined;
        }

        if (campo === 'documento_fiscal' || campo === 'razon_social') {
            return erroresPorFila[index]?.clienteId;
        }

        return erroresPorFila[index]?.[campo];
    };

    const filaTieneError = (index: number): boolean =>
        mostrarErrores && !!erroresPorFila[index] && Object.keys(erroresPorFila[index]).length > 0;

    return (
        <div>
            <div className={`d-flex justify-content-between align-items-center mb-2 gap-2 ${styles.tableToolbar}`}>
                <div className="d-flex align-items-center gap-2 flex-wrap">
                    <button
                        type="button"
                        className="btn btn-outline-secondary btn-sm"
                        onClick={clearFilters}
                        title="Quitar todos los filtros de la tabla"
                    >
                        <FilterX size={16} className="me-1" />
                        Limpiar filtros
                    </button>
                    <span className="text-muted small">
                        Mostrando {visibleRows.length} de {data.length}
                    </span>
                </div>
                <div className="d-flex gap-2">
                <button
                    type="button"
                    className={`btn btn-sm ${styles.scrollButton}`}
                    onClick={scrollLeft}
                    title="Desplazar a la izquierda"
                >
                    <ChevronLeft size={16} className="me-1" /> Izquierda
                </button>
                <button
                    type="button"
                    className={`btn btn-sm ${styles.scrollButton}`}
                    onClick={scrollRight}
                    title="Desplazar a la derecha"
                >
                    Derecha <ChevronRight size={16} className="ms-1" />
                </button>
                </div>
            </div>
            <div ref={tableContainerRef} className={styles.tableResponsive}>
            <table className="table align-middle table-striped-columns mb-0" style={{ width: "100%", minWidth: "3150px" }}>
                <thead className="table-light">
                    <tr>
                        <th scope="col" className={styles.thStickyHeader} style={{ width: "90px", wordBreak: "break-word" }}>Acciones</th>
                        <th scope="col" className={styles.thStickyHeader} style={{ width: "150px", wordBreak: "break-word" }}>Cliente CIF/NIF</th>
                        <th scope="col" className={styles.thStickyHeader} style={{ width: "300px", wordBreak: "break-word" }}>Nombre Cliente</th>
                        <th scope="col" className={styles.thStickyHeader} style={{ width: "330px", wordBreak: "break-word" }}>CUPS</th>
                        <th scope="col" className={styles.thStickyHeader} style={{ width: "200px", wordBreak: "break-word" }}>Dirección</th>
                        <th scope="col" className={styles.thStickyHeader} style={{ width: "90px", wordBreak: "break-word" }}>Tarifa</th>
                        <th scope="col" className={styles.thStickyHeader} style={{ width: "100px", wordBreak: "break-word" }}>Consumo</th>
                        <th scope="col" className={styles.thStickyHeader} style={{ width: "140px", wordBreak: "break-word" }}>Comercializadora</th>
                        <th scope="col" className={styles.thStickyHeader} style={{ width: "160px", wordBreak: "break-word" }}>Producto</th>
                        <th scope="col" className={styles.thStickyHeader} style={{ width: "140px", wordBreak: "break-word", textAlign: "center" }}>Tipo Precio</th>
                        <th scope="col" className={styles.thStickyHeader} style={{ width: "50px", wordBreak: "break-word", textAlign: "center", cursor: "pointer" }} title="Garantía de Origen Verde">GDO</th>
                        <th scope="col" className={styles.thStickyHeader} style={{ width: "160px", wordBreak: "break-word" }}>Anexo</th>
                        <th scope="col" className={styles.thStickyHeader} style={{ width: "50px", wordBreak: "break-word", textAlign: "center" }} title="Permanencia">Perm.</th>
                        <th scope="col" className={styles.thStickyHeader} style={{ width: "120px", wordBreak: "break-word" }}>Fecha Inicio</th>
                        <th scope="col" className={styles.thStickyHeader} style={{ width: "120px", wordBreak: "break-word" }}>Fecha Fin</th>
                        <th scope="col" className={styles.thStickyHeader} style={{ width: "50px", wordBreak: "break-word", textAlign: "center", cursor: "pointer" }} title="Cambio Titular">C.T</th>
                        <th scope="col" className={styles.thStickyHeader} style={{ width: "50px", wordBreak: "break-word", textAlign: "center", cursor: "pointer" }} title="Cambio Potencia">C.P</th>
                        <ServiciosContratoTableHeaders styles={styles} />
                        <th scope="col" className={styles.thStickyHeader} style={{ width: "100px", wordBreak: "break-word", textAlign: "right" }}>Gasto Op (c€/kWh)</th>
                        <th scope="col" className={styles.thStickyHeader} style={{ width: "300px", wordBreak: "break-word", textAlign: "center" }}>Ventana de Precios</th>
                    </tr>
                    <tr>
                        <th className={styles.thStickyFilter} style={{ width: '90px' }} />
                        <th className={styles.thStickyFilter} style={{ width: '150px' }}>
                            <input type="text" className={`form-control form-control-sm ${styles.filterInput}`} placeholder="Filtrar…" value={filters.documento_fiscal} onChange={(e) => setFilters((p) => ({ ...p, documento_fiscal: e.target.value }))} aria-label="Filtrar por CIF/NIF" />
                        </th>
                        <th className={styles.thStickyFilter} style={{ width: '300px' }}>
                            <input type="text" className={`form-control form-control-sm ${styles.filterInput}`} placeholder="Filtrar…" value={filters.razon_social} onChange={(e) => setFilters((p) => ({ ...p, razon_social: e.target.value }))} aria-label="Filtrar por nombre cliente" />
                        </th>
                        <th className={styles.thStickyFilter} style={{ width: '330px' }}>
                            <input type="text" className={`form-control form-control-sm ${styles.filterInput}`} placeholder="Filtrar CUPS…" value={filters.cups_electrico} onChange={(e) => setFilters((p) => ({ ...p, cups_electrico: e.target.value }))} aria-label="Filtrar por CUPS" />
                        </th>
                        <th className={styles.thStickyFilter} style={{ width: '200px' }}>
                            <input type="text" className={`form-control form-control-sm ${styles.filterInput}`} placeholder="Filtrar…" value={filters.direccion} onChange={(e) => setFilters((p) => ({ ...p, direccion: e.target.value }))} aria-label="Filtrar por dirección" />
                        </th>
                        <th className={styles.thStickyFilter} style={{ width: '90px' }}>
                            <input type="text" className={`form-control form-control-sm ${styles.filterInput}`} placeholder="Filtrar…" value={filters.nombreTarifa} onChange={(e) => setFilters((p) => ({ ...p, nombreTarifa: e.target.value }))} aria-label="Filtrar por tarifa" />
                        </th>
                        <th className={styles.thStickyFilter} style={{ width: '100px' }}>
                            <input type="text" className={`form-control form-control-sm ${styles.filterInput}`} placeholder="Filtrar…" value={filters.consumo} onChange={(e) => setFilters((p) => ({ ...p, consumo: e.target.value }))} aria-label="Filtrar por consumo" />
                        </th>
                        <th className={styles.thStickyFilter} style={{ width: '140px' }}>
                            <select className={`form-select form-select-sm ${styles.filterSelect}`} value={filters.comercializadora} onChange={(e) => setFilters((p) => ({ ...p, comercializadora: e.target.value }))} aria-label="Filtrar por comercializadora">
                                <option value="">Todas</option>
                                {comercializadoras.map((com: any) => (
                                    <option key={com.CodCom} value={String(com.CodCom)}>{com.NomComCom}</option>
                                ))}
                            </select>
                        </th>
                        <th className={styles.thStickyFilter} style={{ width: '160px' }}>
                            <select className={`form-select form-select-sm ${styles.filterSelect}`} value={filters.producto} onChange={(e) => setFilters((p) => ({ ...p, producto: e.target.value }))} aria-label="Filtrar por producto">
                                <option value="">Todos</option>
                                {productos.map((producto: any) => (
                                    <option key={producto.CodPro} value={String(producto.CodPro)}>{producto.DesPro}</option>
                                ))}
                            </select>
                        </th>
                        <th className={styles.thStickyFilter} style={{ width: '140px' }}>
                            <select className={`form-select form-select-sm ${styles.filterSelect}`} value={filters.tipoprecio} onChange={(e) => setFilters((p) => ({ ...p, tipoprecio: e.target.value }))} aria-label="Filtrar por tipo precio">
                                <option value="">Todos</option>
                                {tipoprecio.map((registro: any) => (
                                    <option key={registro.id} value={String(registro.id)}>{registro.descripcion}</option>
                                ))}
                            </select>
                        </th>
                        <th className={styles.thStickyFilter} style={{ width: '50px' }}>
                            <select className={`form-select form-select-sm ${styles.filterSelect}`} value={filters.GDO} onChange={(e) => setFilters((p) => ({ ...p, GDO: e.target.value }))} aria-label="Filtrar por GDO">
                                <option value="">—</option>
                                <option value="1">Sí</option>
                                <option value="0">No</option>
                            </select>
                        </th>
                        <th className={styles.thStickyFilter} style={{ width: '160px' }}>
                            <select className={`form-select form-select-sm ${styles.filterSelect}`} value={filters.anexo} onChange={(e) => setFilters((p) => ({ ...p, anexo: e.target.value }))} aria-label="Filtrar por anexo">
                                <option value="">Todos</option>
                                {anexos.map((anexo: any) => (
                                    <option key={anexo.CodAnePro} value={String(anexo.CodAnePro)}>{anexo.DesAnePro}</option>
                                ))}
                            </select>
                        </th>
                        <th className={styles.thStickyFilter} style={{ width: '50px' }}>
                            <select className={`form-select form-select-sm ${styles.filterSelect}`} value={filters.permanencia} onChange={(e) => setFilters((p) => ({ ...p, permanencia: e.target.value }))} aria-label="Filtrar por permanencia">
                                <option value="">—</option>
                                <option value="1">Sí</option>
                                <option value="0">No</option>
                            </select>
                        </th>
                        <th className={styles.thStickyFilter} style={{ width: '120px' }}>
                            <input type="text" className={`form-control form-control-sm ${styles.filterInput}`} placeholder="Filtrar…" value={filters.fechaInicio} onChange={(e) => setFilters((p) => ({ ...p, fechaInicio: e.target.value }))} aria-label="Filtrar por fecha inicio" />
                        </th>
                        <th className={styles.thStickyFilter} style={{ width: '120px' }}>
                            <input type="text" className={`form-control form-control-sm ${styles.filterInput}`} placeholder="Filtrar…" value={filters.fechaFin} onChange={(e) => setFilters((p) => ({ ...p, fechaFin: e.target.value }))} aria-label="Filtrar por fecha fin" />
                        </th>
                        <th className={styles.thStickyFilter} style={{ width: '50px' }}>
                            <select className={`form-select form-select-sm ${styles.filterSelect}`} value={filters.cambioTitular} onChange={(e) => setFilters((p) => ({ ...p, cambioTitular: e.target.value }))} aria-label="Filtrar por cambio titular">
                                <option value="">—</option>
                                <option value="1">Sí</option>
                                <option value="0">No</option>
                            </select>
                        </th>
                        <th className={styles.thStickyFilter} style={{ width: '50px' }}>
                            <select className={`form-select form-select-sm ${styles.filterSelect}`} value={filters.cambioPotencia} onChange={(e) => setFilters((p) => ({ ...p, cambioPotencia: e.target.value }))} aria-label="Filtrar por cambio potencia">
                                <option value="">—</option>
                                <option value="1">Sí</option>
                                <option value="0">No</option>
                            </select>
                        </th>
                        {Array.from({ length: 7 }).map((_, i) => (
                            <th key={`serv-filter-elec-${i}`} className={styles.thStickyFilter} style={{ width: '50px' }} />
                        ))}
                        <th className={styles.thStickyFilter} style={{ width: '100px' }}>
                            <input type="text" className={`form-control form-control-sm ${styles.filterInput}`} placeholder="Filtrar…" value={filters.corpoGo} onChange={(e) => setFilters((p) => ({ ...p, corpoGo: e.target.value }))} aria-label="Filtrar por gasto operativo" />
                        </th>
                        <th className={styles.thStickyFilter} style={{ width: '300px' }}>
                            <input type="text" className={`form-control form-control-sm ${styles.filterInput}`} placeholder="Filtrar ventana…" value={filters.ventana} onChange={(e) => setFilters((p) => ({ ...p, ventana: e.target.value }))} aria-label="Filtrar por ventana de precios" />
                        </th>
                    </tr>
                </thead>
                <tbody>
                    {visibleRows.map(({ row, originalIndex: index }) => {
                        const rowKey = row.tempId || row.cupsId || `idx-${index}`;
                        return (
                        <tr key={`electrico-${rowKey}`} className={`${styles.tableRow} ${filaTieneError(index) ? styles.filaConError : ''}`}>
                             {/* Acciones */}
                            <td style={{ wordBreak: 'break-word', verticalAlign: 'middle', width: '90px' }}>
                                <div className="d-flex gap-1">
                                   {/*
                                    <button
                                        type="button"
                                        className="btn btn-warning btn-sm"
                                        title="Editar CUPS eléctrico"
                                        onClick={() => onEdit(index)}
                                    >
                                        <Pencil size={14} />
                                    </button>
                                    */}
                                    <button
                                        type="button"
                                        className="btn btn-danger btn-sm"
                                        title="Eliminar CUPS eléctrico"
                                        aria-label="Eliminar fila eléctrica"
                                        onClick={() => onDelete(index)}
                                    >
                                        <Trash2 size={14} />
                                    </button>
                                </div>
                            </td>
                            {/* Cliente CIF/NIF */}
                            <td style={{ wordBreak: 'break-word', verticalAlign: 'middle', width: '150px' }}>
                                <TypeaheadClienteConLimpiar<Cliente>
                                    id={obtenerIdDomClienteFila('electrico', index, 'documento_fiscal')}
                                    labelKey="NumCifCli"
                                    placeholder="Buscar CIF/NIF..."
                                    selected={row.clienteId ? clientes.filter((c: Cliente) => Number(c.CodCli) === Number(row.clienteId)) : []}
                                    options={clientes}
                                    isLoading={isLoading}
                                    positionFixed={true}
                                    isInvalid={!!errorCampoCliente(index, 'documento_fiscal')}
                                    errorId={`${obtenerIdDomClienteFila('electrico', index, 'documento_fiscal')}-error`}
                                    onChange={(selected: Cliente[]) => {
                                        const cliente = selected.length > 0 ? selected[0] : null;
                                        if (cliente) {
                                            const updatedElectrico = [...data];
                                            const prevClienteId = updatedElectrico[index]?.clienteId;
                                            const clienteChanged = Number(prevClienteId) !== Number(cliente.CodCli);
                                            updatedElectrico[index] = {
                                                ...updatedElectrico[index],
                                                documento_fiscal: cliente.NumCifCli,
                                                razon_social: cliente.RazSocCli,
                                                clienteId: cliente.CodCli,
                                                ...(clienteChanged
                                                    ? {
                                                        cupsId: '',
                                                        cups_electrico: '',
                                                        direccion: '',
                                                        nombreTarifa: '',
                                                        consumo_kw: '',
                                                        tarifa: '',
                                                        codigo_postal: '',
                                                        EscPunSum: '',
                                                        PlaPunSum: '',
                                                        PuePunSum: '',
                                                        potencia1: '',
                                                        potencia2: '',
                                                        potencia3: '',
                                                        potencia4: '',
                                                        potencia5: '',
                                                        potencia6: '',
                                                        localidad: null,
                                                        provincia: null,
                                                        DesLoc: '',
                                                        DesPro: ''
                                                    }
                                                    : {})
                                            };
                                            onClienteChange(cliente.CodCli, 'electrico', index);
                                            setData("electrico", updatedElectrico);
                                        } else {
                                            onClearCliente(index);
                                        }
                                    }}
                                    onLimpiar={() => onClearCliente(index)}
                                    mostrarBotonLimpiar={!!row.clienteId || !!row.documento_fiscal?.trim() || !!row.razon_social?.trim()}
                                    ariaLabelLimpiar="Limpiar cliente"
                                />
                                <FeedbackCeldaTabla
                                    id={`${obtenerIdDomClienteFila('electrico', index, 'documento_fiscal')}-error`}
                                    mensaje={errorCampoCliente(index, 'documento_fiscal')}
                                />
                            </td>

                            {/* Nombre Cliente */}
                            <td style={{ wordBreak: 'break-all', verticalAlign: 'middle', width: '300px' }}>
                                <TypeaheadClienteConLimpiar<Cliente>
                                    id={obtenerIdDomClienteFila('electrico', index, 'razon_social')}
                                    labelKey="RazSocCli"
                                    placeholder="Buscar Nombre..."
                                    selected={row.clienteId ? clientes.filter((c: Cliente) => Number(c.CodCli) === Number(row.clienteId)) : []}
                                    options={clientes}
                                    isLoading={isLoading}
                                    positionFixed={true}
                                    isInvalid={!!errorCampoCliente(index, 'razon_social')}
                                    errorId={`${obtenerIdDomClienteFila('electrico', index, 'razon_social')}-error`}
                                    onChange={(selected: Cliente[]) => {
                                        const cliente = selected.length > 0 ? selected[0] : null;
                                        if (cliente) {
                                            const updatedElectrico = [...data];
                                            const prevClienteId = updatedElectrico[index]?.clienteId;
                                            const clienteChanged = Number(prevClienteId) !== Number(cliente.CodCli);
                                            updatedElectrico[index] = {
                                                ...updatedElectrico[index],
                                                documento_fiscal: cliente.NumCifCli,
                                                razon_social: cliente.RazSocCli,
                                                clienteId: cliente.CodCli,
                                                ...(clienteChanged
                                                    ? {
                                                        cupsId: '',
                                                        cups_electrico: '',
                                                        direccion: '',
                                                        nombreTarifa: '',
                                                        consumo_kw: '',
                                                        tarifa: '',
                                                        codigo_postal: '',
                                                        EscPunSum: '',
                                                        PlaPunSum: '',
                                                        PuePunSum: '',
                                                        potencia1: '',
                                                        potencia2: '',
                                                        potencia3: '',
                                                        potencia4: '',
                                                        potencia5: '',
                                                        potencia6: ''
                                                    }
                                                    : {})
                                            };
                                            onClienteChange(cliente.CodCli, 'electrico', index);
                                            setData("electrico", updatedElectrico);
                                        } else {
                                            onClearCliente(index);
                                        }
                                    }}
                                    onLimpiar={() => onClearCliente(index)}
                                    mostrarBotonLimpiar={!!row.clienteId || !!row.documento_fiscal?.trim() || !!row.razon_social?.trim()}
                                    ariaLabelLimpiar="Limpiar cliente"
                                />
                                <FeedbackCeldaTabla
                                    id={`${obtenerIdDomClienteFila('electrico', index, 'razon_social')}-error`}
                                    mensaje={errorCampoCliente(index, 'razon_social')}
                                />
                            </td>

                            {/* CUPS */}
                            <td style={{ wordBreak: 'break-all', verticalAlign: 'middle', width: '330px' }}>
                                <div className={styles.cupsInputContainer}>
                                    <Zap size={16} color="#0066cc" />
                                    <Typeahead
                                        id={obtenerIdDomCeldaTabla('electrico', index, 'cups_electrico')}
                                        options={cupsOptionsPorFila[rowKey] || []}
                                        labelKey="codigoCups"
                                        isLoading={cupsLoadingPorFila[rowKey] ?? false}
                                        selected={row.cups_electrico ?
                                            [
                                                (cupsOptionsPorFila[rowKey] || []).find((option: any) => option.codigoCups === row.cups_electrico) || { codigoCups: row.cups_electrico }
                                            ] : []
                                        }
                                        onChange={(selected: any[]) => {
                                            const cups = selected[0] as any;
                                            if (cups) {
                                                onCupsChange(cups, index);
                                            } else {
                                                onClearCups(index);
                                            }
                                        }}
                                        placeholder="Seleccionar CUPS..."
                                        minLength={0}
                                        maxResults={10}
                                        dropup={false}
                                        positionFixed={true}
                                        highlightOnlyResult={true}
                                        isInvalid={!!errorCampo(index, 'cups_electrico')}
                                        inputProps={{
                                            className: `form-control-sm ${errorCampo(index, 'cups_electrico') ? 'is-invalid' : ''}`,
                                            'aria-invalid': !!errorCampo(index, 'cups_electrico'),
                                            'aria-describedby': errorCampo(index, 'cups_electrico')
                                                ? `${obtenerIdDomCeldaTabla('electrico', index, 'cups_electrico')}-error`
                                                : undefined,
                                        }}
                                        style={{ width: '270px', fontSize: '13px', wordBreak: 'break-all' }}
                                    />
                                    <button
                                        type="button"
                                        className="btn btn-outline-secondary btn-sm"
                                        title="Limpiar CUPS eléctrico"
                                        aria-label="Limpiar CUPS eléctrico"
                                        style={{ padding: '2px 6px', fontSize: '10px' }}
                                        onClick={() => onClearCups(index)}
                                    >
                                        <X size={12} />
                                    </button>
                                </div>
                                <FeedbackCeldaTabla
                                    id={`${obtenerIdDomCeldaTabla('electrico', index, 'cups_electrico')}-error`}
                                    mensaje={errorCampo(index, 'cups_electrico')}
                                />
                            </td>

                            {/* Dirección */}
                            <td style={{ wordBreak: 'break-word', verticalAlign: 'middle', width: '200px' }}>
                                {row.direccion || ''}
                            </td>

                            {/* Tarifa */}
                            <td style={{ wordBreak: 'break-word', verticalAlign: 'middle', width: '90px' }}>
                                <input
                                    type="text"
                                    id={obtenerIdDomCeldaTabla('electrico', index, 'tarifa')}
                                    className={`form-control form-control-sm ${styles.readonlyInput} ${errorCampo(index, 'tarifa') ? 'is-invalid' : ''}`}
                                    value={row.nombreTarifa || ''}
                                    readOnly
                                    aria-invalid={!!errorCampo(index, 'tarifa')}
                                />
                                <FeedbackCeldaTabla
                                    id={`${obtenerIdDomCeldaTabla('electrico', index, 'tarifa')}-error`}
                                    mensaje={errorCampo(index, 'tarifa')}
                                />
                            </td>

                            {/* Consumo */}
                            <td style={{ wordBreak: 'break-word', verticalAlign: 'middle', width: '100px' }}>
                                {row.consumo_kw ? `${row.consumo_kw} kWh` : ''}
                            </td>

                            {/* Comercializadora */}
                            <td style={{ wordBreak: 'break-word', verticalAlign: 'middle', width: '140px' }}>
                                <select
                                    id={obtenerIdDomCeldaTabla('electrico', index, 'comercializadora')}
                                    className={`form-select form-select-sm ${styles.selectFullWidth} ${errorCampo(index, 'comercializadora') ? 'is-invalid' : ''}`}
                                    value={row.comercializadora || ''}
                                    onChange={(e) => onFieldChange(index, 'comercializadora', e.target.value)}
                                    aria-invalid={!!errorCampo(index, 'comercializadora')}
                                >
                                    <option value="">Seleccionar...</option>
                                    {comercializadoras.map((com: any) => (
                                        <option key={com.CodCom} value={com.CodCom}>
                                            {com.NomComCom}
                                        </option>
                                    ))}
                                </select>
                                <FeedbackCeldaTabla
                                    id={`${obtenerIdDomCeldaTabla('electrico', index, 'comercializadora')}-error`}
                                    mensaje={errorCampo(index, 'comercializadora')}
                                />
                            </td>

                            {/* Producto */}
                            <td style={{ wordBreak: 'break-word', verticalAlign: 'middle', width: '160px' }}>
                                <select
                                    id={obtenerIdDomCeldaTabla('electrico', index, 'producto')}
                                    className={`form-select form-select-sm ${styles.selectFullWidth} ${errorCampo(index, 'producto') ? 'is-invalid' : ''}`}
                                    value={row.producto || ''}
                                    onChange={(e) => onProductoChange(e, index)}
                                    aria-invalid={!!errorCampo(index, 'producto')}
                                >
                                    <option value="">Seleccionar...</option>
                                    {productos
                                        .filter((producto: any) => producto.CodCom == row.comercializadora)
                                        .map(producto => (
                                            <option key={producto.CodPro} value={producto.CodPro}>
                                                {producto.DesPro}
                                            </option>
                                        ))
                                    }
                                </select>
                                <FeedbackCeldaTabla
                                    id={`${obtenerIdDomCeldaTabla('electrico', index, 'producto')}-error`}
                                    mensaje={errorCampo(index, 'producto')}
                                />
                            </td>

                            {/* Tipo Precio */}
                            <td style={{ width: '140px' }}>
                                <Form.Select
                                    id={obtenerIdDomCeldaTabla('electrico', index, 'tipoprecio')}
                                    name="tipoprecio"
                                    className={`form-select form-select-sm ${errorCampo(index, 'tipoprecio') ? 'is-invalid' : ''}`}
                                    onChange={(e) => onFieldChange(index, 'tipoprecio', e.target.value)}
                                    value={row.tipoprecio || ''}
                                    isInvalid={!!errorCampo(index, 'tipoprecio')}
                                >
                                    <option value="">Seleccione tipo precio</option>
                                    {tipoprecio.map((registro: any) => (
                                        <option key={registro.id} value={registro.id}>
                                            {registro.descripcion}
                                        </option>
                                    ))}
                                </Form.Select>
                                <FeedbackCeldaTabla
                                    id={`${obtenerIdDomCeldaTabla('electrico', index, 'tipoprecio')}-error`}
                                    mensaje={errorCampo(index, 'tipoprecio')}
                                />
                            </td>

                            {/* GDO */}
                            <td style={{ textAlign: 'center', width: '50px' }}>
                                <input
                                    type="checkbox"
                                    style={{ width: '20px', height: '20px', cursor: 'pointer' }}
                                    checked={row.GDO == '1'}
                                    onChange={(e) => onFieldChange(index, 'GDO', e.target.checked ? '1' : '0')}
                                />
                            </td>

                            {/* Anexo */}
                            <td style={{ wordBreak: 'break-word', verticalAlign: 'middle', width: '160px' }}>
                                <select
                                    className={`form-select ${styles.selectFullWidth}`}
                                    value={row.anexo || ''}
                                    onChange={(e) => onAnexoChange(e, index)}
                                >
                                    <option value="">Seleccionar...</option>
                                    {anexos
                                        .filter((anexo: any) => anexo.CodPro == row.producto)
                                        .map((anexo: any) => (
                                            <option key={anexo.CodAnePro} value={anexo.CodAnePro}>
                                                {anexo.DesAnePro}
                                            </option>
                                        ))
                                    }
                                </select>
                            </td>

                            {/* Permanencia */}
                            <td style={{ textAlign: 'center', width: '50px' }}>
                                <input
                                    type="checkbox"
                                    style={{ width: '20px', height: '20px', cursor: 'pointer' }}
                                    checked={row.permanencia == '1'}
                                    onChange={(e) => onFieldChange(index, 'permanencia', e.target.checked ? '1' : '0')}
                                />
                            </td>

                            {/* Fecha Inicio */}
                            <td style={{ wordBreak: 'break-word', verticalAlign: 'middle', width: '120px' }}>
                                <FormDateInputEs
                                    id={obtenerIdDomCeldaTabla('electrico', index, 'fechaInicio')}
                                    className={styles.dateInput}
                                    bsSize="sm"
                                    value={row.fechaInicio || ''}
                                    onChange={(v) => onFieldChange(index, 'fechaInicio', v)}
                                    isInvalid={!!errorCampo(index, 'fechaInicio')}
                                />
                                <FeedbackCeldaTabla
                                    id={`${obtenerIdDomCeldaTabla('electrico', index, 'fechaInicio')}-error`}
                                    mensaje={errorCampo(index, 'fechaInicio')}
                                />
                            </td>

                            {/* Fecha Fin */}
                            <td style={{ wordBreak: 'break-word', verticalAlign: 'middle', width: '120px' }}>
                                <FormDateInputEs
                                    id={obtenerIdDomCeldaTabla('electrico', index, 'fechaFin')}
                                    className={styles.dateInput}
                                    bsSize="sm"
                                    value={row.fechaFin || ''}
                                    onChange={(v) => onFieldChange(index, 'fechaFin', v)}
                                    isInvalid={!!errorCampo(index, 'fechaFin')}
                                />
                                <FeedbackCeldaTabla
                                    id={`${obtenerIdDomCeldaTabla('electrico', index, 'fechaFin')}-error`}
                                    mensaje={errorCampo(index, 'fechaFin')}
                                />
                            </td>

                            {/* Cambio Titular */}
                            <td style={{ textAlign: 'center', width: '50px' }}>
                                <input
                                    type="checkbox"
                                    style={{ width: '20px', height: '20px', cursor: 'pointer' }}
                                    checked={row.cambioTitular == '1'}
                                    onChange={(e) => onFieldChange(index, 'cambioTitular', e.target.checked ? '1' : '0')}
                                />
                            </td>

                            {/* Cambio Potencia */}
                            <td style={{ textAlign: 'center', width: '50px' }}>
                                <input
                                    type="checkbox"
                                    style={{ width: '20px', height: '20px', cursor: 'pointer' }}
                                    checked={row.cambioPotencia == '1'}
                                    onChange={(e) => onFieldChange(index, 'cambioPotencia', e.target.checked ? '1' : '0')}
                                />
                            </td>

                            <ServiciosContratoTableCells
                                row={row}
                                index={index}
                                onFieldChange={onFieldChange}
                                styles={styles}
                            />

                            {/* Gasto Operativo */}
                            <td style={{ wordBreak: 'break-word', verticalAlign: 'middle', width: '100px' }}>
                                <input
                                    type="text"
                                    className="form-control"
                                    style={{ width: '100px', wordBreak: 'break-word', textAlign: 'right' }}
                                    value={row.corpoGo || ''}
                                    onChange={(e) => onFieldChange(index, 'corpoGo', e.target.value)}
                                />
                            </td>

                            {/* Ventana de Precios */}
                            <td style={{ wordBreak: 'break-word', verticalAlign: 'middle', width: '300px', textAlign: 'right' }}>
                                <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                                    <input
                                        type="text"
                                        className="form-control"
                                        style={{ width: '180px', fontSize: '13px' }}
                                        value={row.Id_Tarifa_Automatica || ''}
                                        onChange={(e) => onFieldChange(index, 'Id_Tarifa_Automatica', e.target.value)}
                                    />
                                    <button
                                        type="button"
                                        className="btn btn-outline-primary btn-sm"
                                        onClick={() => setShowModalPrecios(index)}
                                        title="Buscar ventana de precios"
                                        aria-label="Buscar ventana de precios eléctrica"
                                    >
                                        <Search size={16} />
                                    </button>
                                </div>
                                {showModalPrecios === index && (
                                    <div className={styles.dialogContenidoPrecios}>
                                    <ModalPrecios
                                        show={true}
                                        onClose={() => setShowModalPrecios(null)}
                                        onSelect={(selection) => {
                                            let updatedElectrico = [...data];
                                            const patch = buildVentanaRowPatch(selection);
                                            if (isDatosComunes && origenRowHasTarifaParaVentana(row)) {
                                                updatedElectrico = updatedElectrico.map((r) =>
                                                    rowMatchesVentanaTarifaFiltro(row, r) ? { ...r, ...patch } : r
                                                );
                                            } else {
                                                updatedElectrico[index] = {
                                                    ...updatedElectrico[index],
                                                    ...patch,
                                                };
                                            }
                                            setData('electrico', updatedElectrico);
                                            setShowModalPrecios(null);
                                        }}
                                        title="Seleccionar ventana de precios - Eléctrico"
                                        rowData={row}
                                        tipo="electrico"
                                        comercializadoraData={comercializadoras.find(c => c.CodCom == row.comercializadora)}
                                    />
                                    </div>
                                )}
                            </td>


                        </tr>
                    );
                })}
                </tbody>
            </table>
        </div>
        </div>
    );
};

