import React from 'react';
import { Button, Spinner, Table } from 'react-bootstrap';
import type { UseHistorialCupsResult } from '../hooks/useHistorialCups';
import {
    ETIQUETA_ESTADO_CONTRATO,
    ETIQUETA_TIP_SERV,
    HistorialCupsSnapshotElectrico,
    HistorialCupsSnapshotGas,
    TipoCupsHistorial,
} from '../types/historialCups';
import { EneonTabEmptyState } from '../../Shared/Tabs';
import { History } from 'lucide-react';
import styles from '../../PuntosSuministro/CupsTablaInline.module.css';

interface CupsHistorialTabProps {
    tipo: TipoCupsHistorial;
    codCups: number | null;
    panelId: string;
    historial: UseHistorialCupsResult;
    variant?: 'electrico' | 'gas';
}

const formatFecha = (value: string | null | undefined): string => {
    if (!value) {
        return '-';
    }

    try {
        const [year, month, day] = value.split('-').map(Number);
        if (!year || !month || !day) {
            return value;
        }

        return new Date(year, month - 1, day).toLocaleDateString('es-ES');
    } catch {
        return value;
    }
};

const formatNum = (v: number | string | null | undefined): string => {
    if (v === null || v === undefined || v === '') return '-';
    return String(v);
};

const formatEstado = (estado: number | null | undefined, etiquetas: Record<number, string>): string => {
    if (estado == null) {
        return '-';
    }

    return etiquetas[estado] ?? String(estado);
};

const formatTarifa = (
    nombre: string | null | undefined,
    codigo: number | null | undefined
): string => {
    if (nombre) {
        return nombre;
    }

    if (codigo != null) {
        return String(codigo);
    }

    return '-';
};

export default function CupsHistorialTab({
    tipo,
    codCups,
    panelId,
    historial,
    variant,
}: CupsHistorialTabProps): React.ReactElement {
    const variante = variant ?? tipo;
    const { data, loading, error, fetchHistorial, codCupsActivo } = historial;
    const datosListos = codCupsActivo === codCups;

    if (!codCups) {
        return (
            <EneonTabEmptyState
                variant={variante}
                icon={<History size={20} />}
                title="Ningún CUPS seleccionado"
                description="Seleccione un CUPS en Datos actuales o use el selector superior para ver su historial de cambios."
                className="mb-0"
            />
        );
    }

    if ((loading && !datosListos) || (data && !datosListos)) {
        return (
            <div className="text-center py-4" id={panelId} role="tabpanel" aria-busy="true" aria-live="polite">
                <Spinner animation="border" size="sm" role="status" className="me-2" />
                Cargando historial…
            </div>
        );
    }

    if (error) {
        return (
            <div id={panelId} role="tabpanel" aria-live="polite">
                <p className="text-danger mb-2">{error}</p>
                <Button variant="outline-primary" size="sm" onClick={() => void fetchHistorial()}>
                    Reintentar
                </Button>
            </div>
        );
    }

    if (!data?.items?.length) {
        return (
            <EneonTabEmptyState
                variant={variante}
                icon={<History size={20} />}
                title="Sin modificaciones registradas"
                description="Este CUPS aún no tiene entradas en el historial. Los cambios de tarifa, potencia o consumo quedarán registrados al guardar."
                className="mb-0"
            />
        );
    }

    if (tipo === 'electrico') {
        return (
            <div className={styles.contenedorTablaCups} id={panelId} role="tabpanel" tabIndex={0} aria-live="polite">
                <Table bordered hover size="sm" className={`table-striped align-middle ${styles.tablaCups}`}>
                    <thead>
                        <tr>
                            <th>Tarifa</th>
                            <th>P1</th>
                            <th>P2</th>
                            <th>P3</th>
                            <th>P4</th>
                            <th>P5</th>
                            <th>P6</th>
                            <th>Fec. inicio</th>
                            <th>Fec. fin</th>
                            <th>Consumo</th>
                            <th>Tipo servicio</th>
                            <th>Estado</th>
                        </tr>
                    </thead>
                    <tbody>
                        {data.items.map((item) => {
                            const s = item.snapshot as HistorialCupsSnapshotElectrico;
                            return (
                                <tr key={item.codHistorial}>
                                    <td>{formatTarifa(s.nombreTarifa, s.CodTarEle)}</td>
                                    <td>{formatNum(s.PotCon1)}</td>
                                    <td>{formatNum(s.PotCon2)}</td>
                                    <td>{formatNum(s.PotCon3)}</td>
                                    <td>{formatNum(s.PotCon4)}</td>
                                    <td>{formatNum(s.PotCon5)}</td>
                                    <td>{formatNum(s.PotCon6)}</td>
                                    <td>{formatFecha(s.FecIniCon)}</td>
                                    <td>{formatFecha(s.FecFinCon)}</td>
                                    <td>{formatNum(s.ConCup)}</td>
                                    <td>{s.TipServ != null ? (ETIQUETA_TIP_SERV[s.TipServ] ?? s.TipServ) : '-'}</td>
                                    <td>{formatEstado(s.EstConCupEle, ETIQUETA_ESTADO_CONTRATO)}</td>
                                </tr>
                            );
                        })}
                    </tbody>
                </Table>
            </div>
        );
    }

    return (
        <div className={styles.contenedorTablaCups} id={panelId} role="tabpanel" tabIndex={0} aria-live="polite">
            <Table bordered hover size="sm" className={`table-striped align-middle ${styles.tablaCups}`}>
                <thead>
                    <tr>
                        <th>Tarifa</th>
                        <th>Fec. inicio</th>
                        <th>Fec. fin</th>
                        <th>Consumo</th>
                        <th>Tipo servicio</th>
                        <th>Estado</th>
                    </tr>
                </thead>
                <tbody>
                    {data.items.map((item) => {
                        const s = item.snapshot as HistorialCupsSnapshotGas;
                        return (
                            <tr key={item.codHistorial}>
                                <td>{formatTarifa(s.nombreTarifa, s.CodTarGas)}</td>
                                <td>{formatFecha(s.FecIniCon)}</td>
                                <td>{formatFecha(s.FecFinCon)}</td>
                                <td>{formatNum(s.ConCup)}</td>
                                <td>{s.TipServ != null ? (ETIQUETA_TIP_SERV[s.TipServ] ?? s.TipServ) : '-'}</td>
                                <td>{formatEstado(s.EstConCupGas, ETIQUETA_ESTADO_CONTRATO)}</td>
                            </tr>
                        );
                    })}
                </tbody>
            </Table>
        </div>
    );
}
