import React from 'react';
import { Card, OverlayTrigger, Tooltip } from 'react-bootstrap';
import { Flame, MapPin, Pencil, Trash2, Zap } from 'lucide-react';
import { PuntoSuministro } from '../Contratos/Interfaces/Interfaces';
import styles from './PuntoCard.module.css';

interface Props {
  punto: PuntoSuministro & {
    cups_electrico_count?: number;
    cups_gas_count?: number;
    cups_electrico?: any[];
    cupsElectrico?: any[];
    cups_gas?: any[];
    cupsGas?: any[];
  };
  onConsultar: (p: PuntoSuministro) => void;
  onEditar: (p: PuntoSuministro) => void;
  onBorrar: (p: PuntoSuministro) => void;
  searchTermCups?: string;
}

const PuntoCard: React.FC<Props> = ({ punto, onConsultar, onEditar, onBorrar, searchTermCups = '' }) => {
  const cliente = (punto as any).cliente;
  const localidadData = (punto as any).localidad;
  const nombreCliente = cliente?.RazSocCli || cliente?.NomCli || '—';
  const nifCliente = cliente?.NumCifCli || cliente?.NumDocCli || '—';
  const localidad = localidadData?.NomLoc || localidadData?.DesLoc || '—';
  const provincia = localidadData?.provincia?.NomPro || localidadData?.provincia?.DesPro || '—';

  const cupsEleCount =
    punto.cups_electrico_count ??
    (punto as any).cupsElectrico_count ??
    punto.cups_electrico?.length ??
    (punto as any).cupsElectrico?.length ??
    0;
  const cupsGasCount =
    punto.cups_gas_count ??
    (punto as any).cupsGas_count ??
    punto.cups_gas?.length ??
    (punto as any).cupsGas?.length ??
    0;

  const direccionParts = [
    punto.NomViaPunSum,
    punto.NumViaPunSum,
    punto.BloPunSum,
    punto.EscPunSum,
    punto.PlaPunSum,
    punto.PuePunSum,
  ].filter(Boolean);

  const direccion = direccionParts.length ? direccionParts.join(' ') : '—';
  const estadoLabel = punto.EstPunSum === 1 ? 'Activo' : 'Inactivo';
  const estadoClass = punto.EstPunSum === 1 ? 'bg-success' : 'bg-secondary';

  const cupsEleList = (
    punto.cups_electrico ??
    (punto as any).cupsElectrico ??
    []
  ).map((c: any) => c.CUPsEle || c.cups).filter(Boolean);

  const cupsGasList = (
    punto.cups_gas ??
    (punto as any).cupsGas ??
    []
  ).map((c: any) => c.CupsGas || c.cups).filter(Boolean);

  const cleanSearchTerm = searchTermCups.trim().toUpperCase();
  let matchType: 'exact' | 'high_partial' | 'low_partial' | null = null;
  let matchingCups = '';
  let matchPercentage = 0;

  if (cleanSearchTerm) {
    const allCups = [...cupsEleList, ...cupsGasList];
    const exact = allCups.find(c => c.toUpperCase() === cleanSearchTerm);
    if (exact) {
      matchType = 'exact';
      matchingCups = exact;
      matchPercentage = 100;
    } else {
      const partial = allCups.find(c => c.toUpperCase().includes(cleanSearchTerm));
      if (partial) {
        matchingCups = partial;
        matchPercentage = Math.round((cleanSearchTerm.length / partial.length) * 100);
        if (matchPercentage > 35) {
          matchType = 'high_partial';
        } else {
          matchType = 'low_partial';
        }
      }
    }
  }

  const renderTooltipEle = (props: any) => (
    <Tooltip id="tooltip-electrico" {...props} style={{ ...props.style, zIndex: 9999 }}>
      <div className="text-start p-1" style={{ fontSize: '0.8rem' }}>
        <strong className="d-block mb-1 border-bottom pb-1">CUPS Eléctricos:</strong>
        {cupsEleList.length > 0 ? (
          <ul className="list-unstyled mb-0 ps-0">
            {cupsEleList.map((c, i) => (
              <li key={i} className="font-monospace text-warning py-0.5" style={{ letterSpacing: '0.05em' }}>
                ⚡ {c}
              </li>
            ))}
          </ul>
        ) : (
          <span className="text-muted">Sin CUPS asociados</span>
        )}
      </div>
    </Tooltip>
  );

  const renderTooltipGas = (props: any) => (
    <Tooltip id="tooltip-gas" {...props} style={{ ...props.style, zIndex: 9999 }}>
      <div className="text-start p-1" style={{ fontSize: '0.8rem' }}>
        <strong className="d-block mb-1 border-bottom pb-1">CUPS Gas:</strong>
        {cupsGasList.length > 0 ? (
          <ul className="list-unstyled mb-0 ps-0">
            {cupsGasList.map((c, i) => (
              <li key={i} className="font-monospace text-danger py-0.5" style={{ letterSpacing: '0.05em' }}>
                🔥 {c}
              </li>
            ))}
          </ul>
        ) : (
          <span className="text-muted">Sin CUPS asociados</span>
        )}
      </div>
    </Tooltip>
  );

  return (
    <Card
      className={`${styles.tarjeta} shadow-sm card-3d ${matchType ? '' : 'border-0'}`}
      role="button"
      tabIndex={0}
      style={{
        boxShadow: matchType === 'exact'
          ? '0 0 18px rgba(25, 135, 84, 0.95)'
          : matchType === 'high_partial'
            ? '0 0 16px rgba(253, 126, 20, 0.95)'
            : matchType === 'low_partial'
              ? '0 0 12px rgba(250, 204, 21, 0.95)'
              : undefined,
        border: matchType === 'exact'
          ? '2px solid #198754'
          : matchType === 'high_partial'
            ? '2px solid #fd7e14'
            : matchType === 'low_partial'
              ? '2px solid #facc15'
              : undefined,
        transition: 'all 0.3s ease-in-out'
      }}
      onClick={() => onConsultar(punto)}
      onKeyDown={(event) => {
        if (event.key === 'Enter' || event.key === ' ') {
          event.preventDefault();
          onConsultar(punto);
        }
      }}
      aria-label={`Consultar punto de ${nombreCliente}, ${direccion}`}
    >
      <Card.Header className={styles.cabecera}>
        <h3 className={styles.tituloCliente}>{nombreCliente}</h3>
        <span className={`badge ${estadoClass} ${styles.badgeEstado}`}>{estadoLabel}</span>
      </Card.Header>
      <Card.Body className={styles.cuerpo}>
        <div className={styles.contenido}>
          <div className={styles.filaNif}>
            NIF: <strong>{nifCliente}</strong>
          </div>
          <div className={styles.filaDireccion}>
            <MapPin size={14} className={styles.iconoMapa} aria-hidden="true" />
            <div className={styles.textoDireccion}>
              <p className={styles.lineaDireccion}>{direccion}</p>
              <p className={styles.lineaLocalidad}>
                {localidad} — {provincia}
              </p>
            </div>
          </div>
          {matchType && (
            <div 
              className="alert py-1.5 px-2 mb-2 rounded d-flex align-items-center gap-1.5" 
              style={{ 
                fontSize: '0.8rem', 
                border: matchType === 'exact' 
                  ? '1px dashed #198754' 
                  : matchType === 'high_partial' 
                    ? '1px dashed #fd7e14' 
                    : '1px dashed #eab308', 
                color: matchType === 'exact' 
                  ? '#0f5132' 
                  : matchType === 'high_partial' 
                    ? '#c2410c' 
                    : '#854d0e', 
                backgroundColor: matchType === 'exact' 
                  ? '#d1e7dd' 
                  : matchType === 'high_partial' 
                    ? '#ffedd5' 
                    : '#fef9c3' 
              }} 
              onClick={(e) => e.stopPropagation()}
            >
              <span aria-hidden="true">
                {matchType === 'exact' ? '✅' : matchType === 'high_partial' ? '⚠️' : 'ℹ️'}
              </span>
              <div className="text-truncate">
                {matchType === 'exact' 
                  ? 'CUPS Exacto: ' 
                  : matchType === 'high_partial' 
                    ? `Coincidencia CUPS (${matchPercentage}%): ` 
                    : `Coincidencia parcial (${matchPercentage}%): `}
                <strong className="font-monospace">{matchingCups}</strong>
              </div>
            </div>
          )}

          <div className={styles.badgesCups}>
            <OverlayTrigger
              placement="top"
              delay={{ show: 150, hide: 150 }}
              overlay={renderTooltipEle}
            >
              <span className={`badge bg-light text-dark ${styles.badgeCups}`} style={{ cursor: 'pointer' }} onClick={(e) => e.stopPropagation()}>
                <Zap size={14} aria-hidden="true" /> {cupsEleCount} eléctricos
              </span>
            </OverlayTrigger>

            <OverlayTrigger
              placement="top"
              delay={{ show: 150, hide: 150 }}
              overlay={renderTooltipGas}
            >
              <span className={`badge bg-light text-dark ${styles.badgeCups}`} style={{ cursor: 'pointer' }} onClick={(e) => e.stopPropagation()}>
                <Flame size={14} aria-hidden="true" /> {cupsGasCount} gas
              </span>
            </OverlayTrigger>
          </div>
        </div>
      </Card.Body>
      <Card.Footer className={styles.pie}>
        <button
          type="button"
          className="btn btn-sm btn-black"
          title="Editar punto"
          aria-label={`Editar punto de ${nombreCliente}`}
          onClick={(e) => {
            e.stopPropagation();
            onEditar(punto);
          }}
        >
          <Pencil size={14} aria-hidden="true" />
        </button>
        <button
          type="button"
          className="btn btn-sm btn-black"
          title="Borrar punto"
          aria-label={`Borrar punto de ${nombreCliente}`}
          onClick={(e) => {
            e.stopPropagation();
            onBorrar(punto);
          }}
        >
          <Trash2 size={14} aria-hidden="true" />
        </button>
      </Card.Footer>
    </Card>
  );
};

export default PuntoCard;
