﻿import React from 'react';
import { Row, Col, Table } from 'react-bootstrap';
import {
    SipsResponse,
    ConsumoLuzRow,
    ConsumoGasRow,
    isLuzResponse,
    isGasResponse,
    isElectricityTipo,
    formatSipsNumber,
    consumoTotalLuz,
    consumoTotalGas,
    toNumber,
} from '../../types';
import styles from '../../Sips.module.css';

interface Props {
    result: SipsResponse | null;
    tipoServicio: string;
}

interface ResumenCardProps {
    label: string;
    value: string;
    large?: boolean;
}

const ResumenCard: React.FC<ResumenCardProps> = ({ label, value, large = false }) => (
    <div
        className={styles.tarjetaResumen}
        role="group"
        tabIndex={0}
        aria-label={`${label}: ${value}`}
    >
        <span className={styles.tarjetaResumenLabel}>{label}</span>
        <strong className={`${styles.tarjetaResumenValor} ${large ? 'fs-5' : ''}`}>{value}</strong>
    </div>
);

export const SipsResumenLecturas: React.FC<{ result: SipsResponse }> = ({ result }) => {
    if (isLuzResponse(result)) {
        const { lecturas } = result;

        return (
            <Row className="g-3">
                <Col md={3}>
                    <ResumenCard
                        label="Consumo anual total"
                        value={`${formatSipsNumber(lecturas.LastTotalYearkWh)} kWh`}
                        large
                    />
                </Col>
                {[1, 2, 3, 4, 5, 6].map((p) => {
                    const value = lecturas[`LastTotalYearkWh_p${p}` as keyof typeof lecturas];
                    if (toNumber(value as number) === 0 && p > 3) {
                        return null;
                    }

                    return (
                        <Col md={3} key={p}>
                            <ResumenCard
                                label={`Periodo P${p}`}
                                value={`${formatSipsNumber(value as number)} kWh`}
                            />
                        </Col>
                    );
                })}
            </Row>
        );
    }

    const { lecturas } = result;

    return (
        <Row className="g-3">
            <Col md={3}>
                <ResumenCard
                    label="Consumo anual total"
                    value={`${formatSipsNumber(lecturas.kWhAnual)} kWh`}
                    large
                />
            </Col>
            <Col md={3}>
                <ResumenCard label="Consumo P1" value={`${formatSipsNumber(lecturas.kWhAnual_p1)} kWh`} />
            </Col>
            <Col md={3}>
                <ResumenCard label="Consumo P2" value={`${formatSipsNumber(lecturas.kWhAnual_p2)} kWh`} />
            </Col>
            <Col md={3}>
                <ResumenCard
                    label="Caudal máx. diario"
                    value={`${formatSipsNumber(lecturas.Caudal_Max_Diario_Wh)} kWh/d`}
                />
            </Col>
            <Col md={3}>
                <ResumenCard
                    label="Caudal máx. horario"
                    value={`${formatSipsNumber(lecturas.Caudal_Max_Horario_Wh)} kWh/h`}
                />
            </Col>
        </Row>
    );
};

function EmptyTableMessage({ colSpan, message }: { colSpan: number; message: string }) {
    return (
        <tr>
            <td colSpan={colSpan}>
                <div className={styles.estadoVacioTabla} role="status" tabIndex={0}>
                    {message}
                </div>
            </td>
        </tr>
    );
}

function TablaConsumoWrapper({ caption, children }: { caption: string; children: React.ReactNode }) {
    return (
        <div
            className={styles.tablaConsumosWrapper}
            role="region"
            aria-label={caption}
            tabIndex={-1}
        >
            {children}
        </div>
    );
}

export const SipsTablaConsumo: React.FC<Props> = ({ result, tipoServicio }) => {
    const isLuz = result ? isLuzResponse(result) : isElectricityTipo(tipoServicio);
    const registrosLuz = result && isLuzResponse(result) ? result.selectFinal : [];
    const registrosGas = result && isGasResponse(result) ? result.selectFinal : [];

    if (!result) {
        return (
            <TablaConsumoWrapper caption="Historial de consumo SIPS">
                <Table bordered className={`align-middle mb-0 ${styles.tablaConsumos}`}>
                    <caption className="visually-hidden">Historial de consumo SIPS</caption>
                    <thead className="table-light">
                        <tr>
                            <th scope="col" className={styles.thStickyHeader}>Fecha Inicio</th>
                            <th scope="col" className={styles.thStickyHeader}>Fecha Fin</th>
                            <th scope="col" className={styles.thStickyHeader}>Consumo Total</th>
                        </tr>
                    </thead>
                    <tbody>
                        <EmptyTableMessage
                            colSpan={3}
                            message="Ingrese un CUPS y consulte para ver el historial"
                        />
                    </tbody>
                </Table>
            </TablaConsumoWrapper>
        );
    }

    if (isLuz) {
        return (
            <TablaConsumoWrapper caption="Historial de consumo eléctrico SIPS">
                <Table bordered striped hover className={`align-middle mb-0 ${styles.tablaConsumos}`}>
                    <caption className="visually-hidden">Historial de consumo eléctrico SIPS</caption>
                    <thead className="table-light">
                        <tr>
                            <th scope="col" className={styles.thStickyHeader}>Fecha Inicio</th>
                            <th scope="col" className={styles.thStickyHeader}>Fecha Fin</th>
                            <th scope="col" className={styles.thStickyHeader}>Tarifa</th>
                            <th scope="col" className={`${styles.thStickyHeader} text-end`}>P1</th>
                            <th scope="col" className={`${styles.thStickyHeader} text-end`}>P2</th>
                            <th scope="col" className={`${styles.thStickyHeader} text-end`}>P3</th>
                            <th scope="col" className={`${styles.thStickyHeader} text-end`}>P4</th>
                            <th scope="col" className={`${styles.thStickyHeader} text-end`}>P5</th>
                            <th scope="col" className={`${styles.thStickyHeader} text-end`}>P6</th>
                            <th scope="col" className={`${styles.thStickyHeader} text-end`}>Consumo Total</th>
                        </tr>
                    </thead>
                    <tbody>
                        {registrosLuz.length === 0 ? (
                            <EmptyTableMessage
                                colSpan={10}
                                message="No hay registros de consumo para este CUPS."
                            />
                        ) : (
                            (registrosLuz as ConsumoLuzRow[]).map((row) => {
                                const total = formatSipsNumber(consumoTotalLuz(row));
                                return (
                                    <tr
                                        key={row.id}
                                        tabIndex={0}
                                        aria-label={`Lectura del ${row.FLectAntM1} al ${row.FLectM1}, tarifa ${row.Tarifa || 'sin dato'}, consumo total ${total} kWh`}
                                    >
                                        <td>{row.FLectAntM1}</td>
                                        <td>{row.FLectM1}</td>
                                        <td>{row.Tarifa || '—'}</td>
                                        <td className="text-end">{formatSipsNumber(row.CActP1M1)}</td>
                                        <td className="text-end">{formatSipsNumber(row.CActP2M1)}</td>
                                        <td className="text-end">{formatSipsNumber(row.CActP3M1)}</td>
                                        <td className="text-end">{formatSipsNumber(row.CActP4M1)}</td>
                                        <td className="text-end">{formatSipsNumber(row.CActP5M1)}</td>
                                        <td className="text-end">{formatSipsNumber(row.CActP6M1)}</td>
                                        <td className="text-end fw-semibold">{total}</td>
                                    </tr>
                                );
                            })
                        )}
                    </tbody>
                </Table>
            </TablaConsumoWrapper>
        );
    }

    return (
        <TablaConsumoWrapper caption="Historial de consumo gas SIPS">
            <Table bordered striped hover className={`align-middle mb-0 ${styles.tablaConsumos}`}>
                <caption className="visually-hidden">Historial de consumo gas SIPS</caption>
                <thead className="table-light">
                    <tr>
                        <th scope="col" className={styles.thStickyHeader}>Fecha Inicio</th>
                        <th scope="col" className={styles.thStickyHeader}>Fecha Fin</th>
                        <th scope="col" className={styles.thStickyHeader}>Peaje</th>
                        <th scope="col" className={`${styles.thStickyHeader} text-end`}>Consumo P1</th>
                        <th scope="col" className={`${styles.thStickyHeader} text-end`}>Consumo P2</th>
                        <th scope="col" className={`${styles.thStickyHeader} text-end`}>Consumo Total</th>
                        <th scope="col" className={`${styles.thStickyHeader} text-end`}>Caudal Medio</th>
                        <th scope="col" className={`${styles.thStickyHeader} text-end`}>Caudal Máx. Día</th>
                        <th scope="col" className={`${styles.thStickyHeader} text-end`}>% Nocturno</th>
                    </tr>
                </thead>
                <tbody>
                    {registrosGas.length === 0 ? (
                        <EmptyTableMessage
                            colSpan={9}
                            message="No hay registros de consumo para este CUPS."
                        />
                    ) : (
                        (registrosGas as ConsumoGasRow[]).map((row) => {
                            const total = formatSipsNumber(consumoTotalGas(row));
                            return (
                                <tr
                                    key={row.id}
                                    tabIndex={0}
                                    aria-label={`Lectura del ${row.Fec_Ini_Consumo} al ${row.Fec_Fin_consumo}, peaje ${row.Cod_Peaje || 'sin dato'}, consumo total ${total} kWh`}
                                >
                                    <td>{row.Fec_Ini_Consumo}</td>
                                    <td>{row.Fec_Fin_consumo}</td>
                                    <td>{row.Cod_Peaje || '—'}</td>
                                    <td className="text-end">{formatSipsNumber(row.Consumo_kWh_P1)}</td>
                                    <td className="text-end">{formatSipsNumber(row.Consumo_kWh_P2)}</td>
                                    <td className="text-end fw-semibold">{total}</td>
                                    <td className="text-end">{formatSipsNumber(row.Caudal_Medio_kWhd)}</td>
                                    <td className="text-end">{formatSipsNumber(row.Caudal_Max_Dia_kWhd)}</td>
                                    <td className="text-end">{formatSipsNumber(row.Porcentaje_Consumo_Nocturno)}</td>
                                </tr>
                            );
                        })
                    )}
                </tbody>
            </Table>
        </TablaConsumoWrapper>
    );
};
