import React from 'react';
import { Form, Badge, InputGroup, Button } from 'react-bootstrap';
import { Bolt, Flame, MapPin, User, Search } from 'lucide-react';
import { ActionsColumn } from './ActionsColumn';
import { ESTADOS_CONTRATO } from '../../Interfaces/Interfaces';
import ModalPrecios from './ModalPrecios';
import { buildVentanaRowPatch } from '../../ComponentesComunes/ventanaPreciosUtils';
import FormDateInputEs from '../../../../../Components/Common/FormDateInputEs';

/** Columna OkCom: `estado_sinc_okcom` en T_Propuesta_Comercial_CUPs (null/0 → N/A, 1 → OKCOM). */
function formatOkComLabel(estado: unknown): string {
  if (estado === 1 || estado === '1') {
    return 'OKCOM';
  }
  return 'N/A';
}

interface CupsTableRowProps {
  cups: any;
  rowId: string;
  isEditing: boolean;
  editData: any;
  formatFecha: (fecha: string | undefined) => string;
  getEstadoContratoLabel: (estado: number) => string;
  comercializadoras: any[];
  productos: any[];
  anexos: any[];
  onFieldChange: (field: string, value: any) => void;
  onEdit: () => void;
  onSave: () => void;
  onCancel: () => void;
  onDelete: () => void;
  tipo: 'electrico' | 'gas';
  isMultiCliente?: boolean;
  showModalPrecios: string | null;
  onShowModalPrecios: (rowId: string) => void;
  onCloseModalPrecios: () => void;
}

/**
 * Componente de fila de tabla para CUPS (eléctrico o gas)
 */
export const CupsTableRow: React.FC<CupsTableRowProps> = ({
  cups,
  rowId,
  isEditing,
  editData,
  formatFecha,
  getEstadoContratoLabel,
  comercializadoras,
  productos,
  anexos,
  onFieldChange,
  onEdit,
  onSave,
  onCancel,
  onDelete,
  tipo,
  isMultiCliente = false,
  showModalPrecios,
  onShowModalPrecios,
  onCloseModalPrecios
}) => {
  const isElectric = tipo === 'electrico';
  const puntoSuministro = cups.punto_suministro;
  const cliente = puntoSuministro?.cliente;

  // Obtener comercializadora y CodigoServicioProducto
  const codComercializadora = cups.CodCom || cups.comercializadora?.CodCom || editData.comercializadora;
  const comercializadora = comercializadoras.find(c => c.CodCom == codComercializadora);


  // Mostrar botón de búsqueda solo si es servicio Corporativo (CO)

  // Obtener el CUPS correcto según el tipo
  const cupsData: any = isElectric
    ? (cups?.CupEle ?? cups?.cups_electrico)
    : (cups?.CupGas ?? cups?.cups_gas);


  const cupsCode = isElectric
    ? (cupsData?.CUPsEle ?? cupsData?.CupsEle ?? 'N/A')
    : (cupsData?.CupsGas ?? cupsData?.CUPsGas ?? 'N/A');

  const tarifa = isElectric
    ? (cups?.tarifa_electrica?.NomTarEle ?? cups?.tarifaElectrica?.NomTarEle ?? 'N/A')
    : (cups?.tarifa_gas?.NomTarGas ?? cups?.tarifa_gas?.DesTarGas ?? cups?.tarifaGas?.NomTarGas ?? cups?.tarifaGas?.DesTarGas ?? 'N/A');

  const consumo = (cupsData?.ConAnuCup ?? cups?.ConCup ?? 'N/A');
  const unidad = isElectric ? 'kWh' : 'm³';

  return (
    <tr className={cups.NrContratoAudax == "0" ? 'bg-warning' : 'bg-default'}>
      {/* CUPS */}
      <td>
        <div className="d-flex align-items-center">
          {isElectric ? (
            <Bolt size={16} className="me-1 text-primary" />
          ) : (
            <Flame size={16} className="me-1 text-warning" />
          )}
          <span className="fw-medium">{cupsCode}</span>
        </div>
      </td>

      {/* Columnas de cliente (solo para multi-cliente) */}
      {isMultiCliente && (
        <>
          <td>
            {cliente ? (
              <div className="d-flex align-items-center">
                <User size={16} className="me-1 text-secondary" />
                <span className="fw-medium">{cliente.CodCli}</span>
              </div>
            ) : 'N/A'}
          </td>
          <td>{cliente?.NumCifCli}</td>
          <td>{cliente?.RazSocCli}</td>
        </>
      )}

      {/* Dirección */}
      <td>
        {puntoSuministro ? (
          <div className="d-flex align-items-start">
            <MapPin size={16} className="me-1 text-secondary mt-1" />
            <div>
              <div>{puntoSuministro.NomViaPunSum} {puntoSuministro.NumViaPunSum}</div>
              <small className="text-muted">
                {puntoSuministro?.localidad ? `${puntoSuministro.localidad.DesLoc}` : ''}
                {puntoSuministro?.CPLocSoc ? ` (${puntoSuministro.CPLocSoc})` : ''}
              </small>
            </div>
          </div>
        ) : 'N/A'}
      </td>

      {/* Tarifa */}
      <td>{tarifa}</td>

      {/* Tipo de Precio */}
      <td>
        {cups.TipPre == 1 ? 'Fijo' : cups.TipPre == 2 ? 'Indexado' : 'N/A'}
      </td>

      {/* Consumo */}
      <td>{consumo} {unidad}</td>

      {/* Potencias (solo para eléctrico) */}
      {isElectric && (
        <td>
          <div className="d-flex gap-1">
            {cups.PotEleConP1 && <small><strong>P1:</strong> {cups.PotEleConP1} kW</small>}
            {cups.PotEleConP2 && <small><strong>P2:</strong> {cups.PotEleConP2} kW</small>}
            {cups.PotEleConP3 && <small><strong>P3:</strong> {cups.PotEleConP3} kW</small>}
            {cups.PotEleConP4 && <small><strong>P4:</strong> {cups.PotEleConP4} kW</small>}
            {cups.PotEleConP5 && <small><strong>P5:</strong> {cups.PotEleConP5} kW</small>}
            {cups.PotEleConP6 && <small><strong>P6:</strong> {cups.PotEleConP6} kW</small>}
            {!cups.PotEleConP1 && !cups.PotEleConP2 && !cups.PotEleConP3 &&
             !cups.PotEleConP4 && !cups.PotEleConP5 && !cups.PotEleConP6 && 'N/A'}
          </div>
        </td>
      )}

      {/* Comercializadora */}
      <td>
        {isEditing ? (
          <Form.Select
            size="sm"
            value={editData.comercializadora || ''}
            onChange={(e) => onFieldChange('comercializadora', e.target.value)}
          >
            <option value="">Seleccionar</option>
            {comercializadoras.map(com => (
              <option key={com.CodCom} value={com.CodCom}>{com.RazSocCom}</option>
            ))}
          </Form.Select>
        ) : (
          cups.comercializadora?.RazSocCom || 'N/A'
        )}
      </td>

      {/* Producto */}
      <td>
        {isEditing ? (
          <Form.Select
            size="sm"
            value={editData.producto || ''}
            onChange={(e) => onFieldChange('producto', e.target.value)}
          >
            <option value="">Seleccionar</option>
            {productos
              .filter(p => p.CodCom == editData.comercializadora)
              .map(p => (
                <option key={p.CodPro} value={p.CodPro}>{p.DesPro}</option>
              ))}
          </Form.Select>
        ) : (
          cups.producto?.DesPro || 'N/A'
        )}
      </td>

      {/* Anexo */}
      <td>
        {isEditing ? (
          <Form.Select
            size="sm"
            value={editData.anexo || ''}
            onChange={(e) => onFieldChange('anexo', e.target.value)}
          >
            <option value="">Seleccionar</option>
            {anexos
              .filter(a => a.CodPro == editData.producto)
              .map(a => (
                <option key={a.CodAnePro} value={a.CodAnePro}>{a.DesAnePro}</option>
              ))}
          </Form.Select>
        ) : (
          cups.anexo_producto?.DesAnePro || 'N/A'
        )}
      </td>

      {/* Permanencia */}
      <td className="text-center align-middle">
        {isEditing ? (
          <input
            type="checkbox"
            className="form-check-input"
            checked={editData.Permanencia === '1' || editData.Permanencia === 1 || editData.Permanencia === true}
            onChange={(e) => onFieldChange('Permanencia', e.target.checked ? '1' : '0')}
            style={{ width: '20px', height: '20px', cursor: 'pointer' }}
          />
        ) : (
          cups.Permanencia == '1' || cups.Permanencia === 1 ? (
            <Badge bg="success">Sí</Badge>
          ) : (
            <Badge bg="secondary">No</Badge>
          )
        )}
      </td>

      {/* GDO */}
      <td className="text-center align-middle">
        {isEditing ? (
          <input
            type="checkbox"
            className="form-check-input"
            checked={editData.GDO === '1' || editData.GDO === 1 || editData.GDO === true}
            onChange={(e) => onFieldChange('GDO', e.target.checked ? '1' : '0')}
            style={{ width: '20px', height: '20px', cursor: 'pointer' }}
          />
        ) : (
          cups.GDO == '1' || cups.GDO === 1 ? (
            <Badge bg="success">Sí</Badge>
          ) : (
            <Badge bg="secondary">No</Badge>
          )
        )}
      </td>

      {/* Valor GDO */}
      <td className="text-center align-middle">
        {cups.valorGDO || cups.Valor_GDO || cups.valor_gdo || '-'}
      </td>

      {/* Cambio Titular */}
      <td className="text-center align-middle">
        {isEditing ? (
          <input
            type="checkbox"
            className="form-check-input"
            checked={editData.CambioTitular === '1' || editData.CambioTitular === 1 || editData.CambioTitular === true}
            onChange={(e) => onFieldChange('CambioTitular', e.target.checked ? '1' : '0')}
            style={{ width: '20px', height: '20px', cursor: 'pointer' }}
          />
        ) : (
          cups.CambioTitular == '1' || cups.CambioTitular === 1 ? (
            <Badge bg="success">Sí</Badge>
          ) : (
            <Badge bg="secondary">No</Badge>
          )
        )}
      </td>

      {/* Cambio Potencia */}
      <td className="text-center align-middle">
        {isEditing ? (
          <input
            type="checkbox"
            className="form-check-input"
            checked={editData.CambioPotencia === '1' || editData.CambioPotencia === 1 || editData.CambioPotencia === true}
            onChange={(e) => onFieldChange('CambioPotencia', e.target.checked ? '1' : '0')}
            style={{ width: '20px', height: '20px', cursor: 'pointer' }}
          />
        ) : (
          cups.CambioPotencia == '1' || cups.CambioPotencia === 1 ? (
            <Badge bg="success">Sí</Badge>
          ) : (
            <Badge bg="secondary">No</Badge>
          )
        )}
      </td>

      {/* Ventana de Precios (Id_Tarifa_Automatica) */}
      <td>
        <InputGroup size="sm">
          <Form.Control
            type="text"
            value={
              isEditing
                ? (editData.Id_Tarifa_Automatica ?? cups.Id_Tarifa_Automatica ?? '')
                : (cups.Id_Tarifa_Automatica || '')
            }
            readOnly
            style={{ background: '#f8f9fa', fontSize: '13px' }}
          />
          <Button
            variant="outline-primary"
            size="sm"
            onClick={() => onShowModalPrecios(rowId)}
            title="Buscar ventana de precios"
            disabled={!isEditing}
          >
            <Search size={16} />
          </Button>
        </InputGroup>

          {/* Solo esta fila monta el modal: showModalPrecios guarda el rowId activo */}
          {showModalPrecios === rowId && (
            <ModalPrecios
              show
              onClose={onCloseModalPrecios}
              onSelect={(selection) => {
                const patch = buildVentanaRowPatch(selection, { editionMode: true });
                Object.entries(patch).forEach(([field, value]) => onFieldChange(field, value));
                onCloseModalPrecios();
              }}
              title={`Seleccionar ventana de precios - ${isElectric ? 'Eléctrico' : 'Gas'}`}
              rowData={{
                codigoServicioProducto: cups.producto?.CodigoServicio,
                tipoprecio: cups.TipPre ?? editData.tipoprecio,
                tarifa: cups.CodTar,
                nombreTarifa: isElectric
                  ? (cups.tarifa_electrica?.NomTarEle || cups.tarifaElectrica?.NomTarEle)
                  : (cups.tarifa_gas?.NomTarGas || cups.tarifaGas?.NomTarGas)
              }}
              tipo={tipo}
              comercializadoraData={comercializadora}
            />
          )}
        </td>

      {/* Fecha Activación */}
      <td>
        {isEditing ? (
          <FormDateInputEs
            bsSize="sm"
            value={editData.FecActCUPs || ''}
            onChange={(v) => onFieldChange('FecActCUPs', v)}
          />
        ) : (
          formatFecha(cups.FecActCUPs)
        )}
      </td>

      {/* Fecha Vencimiento */}
      <td>
        {isEditing ? (
          <FormDateInputEs
            bsSize="sm"
            value={editData.FecVenCUPs || ''}
            onChange={(v) => onFieldChange('FecVenCUPs', v)}
          />
        ) : (
          formatFecha(cups.FecVenCUPs)
        )}
      </td>

      {/* N° Contrato */}
      <td>
        <div className="d-flex align-items-center justify-content-center">
          <span className="text-black">{cups.NrContratoAudax}</span>
        </div>
      </td>

      {/* OkCom (después de N° Contrato Comercializadora) */}
      <td className="text-center">
        <span className="fw-medium text-nowrap">{formatOkComLabel(cups.estado_sinc_okcom)}</span>
      </td>

      {/* Estado Contrato */}
      <td>
        {isEditing ? (
          <Form.Select
            size="sm"
            value={editData.EstConCups || 1}
            onChange={(e) => onFieldChange('EstConCups', parseInt(e.target.value))}
          >
            {ESTADOS_CONTRATO.map(estado => (
              <option key={estado.key} value={estado.key}>
                {estado.valor}
              </option>
            ))}
          </Form.Select>
        ) : (
          <Badge bg={cups.EstConCups === 1 ? 'success' : cups.EstConCups === 2 ? 'info' : cups.EstConCups === 3 ? 'warning' : 'danger'}>
            {getEstadoContratoLabel(cups.EstConCups || 1)}
          </Badge>
        )}
      </td>

      {/* Acciones */}
      <td>
        <ActionsColumn
          isEditing={isEditing}
          onEdit={onEdit}
          onSave={onSave}
          onCancel={onCancel}
          onDelete={onDelete}
        />
      </td>
    </tr>
  );
};

