import React, { useState, useEffect, useMemo } from 'react';
import { Modal, Button, Table, Spinner } from 'react-bootstrap';
import axios from 'axios';
import Swal from 'sweetalert2';
import estilosFoco from './Shared/estilosFocoAccesible.module.css';
import {
    VentanaOption,
    VentanaSeleccion,
    isAdxVentanaProvider,
    ventanaOptionToSelection,
} from './ComponentesComunes/ventanaPreciosUtils';

export type { VentanaOption, VentanaSeleccion } from './ComponentesComunes/ventanaPreciosUtils';

/**
 * Valor del `<select name="tipoprecio">` por fila: 1 Fijo, 2 Indexado (API Audax).
 * Si llega 0/1 legacy desde BD, se mapea a 1/2.
 */
export function tipoContratoDesdeTipoprecio(tipoprecio: unknown): string {
    if (tipoprecio === undefined || tipoprecio === null || tipoprecio === '') {
        return '';
    }
    const s = String(tipoprecio).trim();
    if (s === '1' || s === '2') {
        return s;
    }
    const n = parseInt(s, 10);
    if (Number.isNaN(n)) {
        return '';
    }
    if (n === 0 || n === 1) {
        return n === 0 ? '1' : '2';
    }
    if (n === 2) {
        return '2';
    }
    return '';
}

interface ModalPreciosProps {
    show: boolean;
    onClose: () => void;
    /** Si `actualizarFechas` es false en la selección, el padre solo aplica ventana ADX/Audax, no fechas. */
    onSelect: (selection: VentanaSeleccion) => void;
    title?: string;
    rowData: Record<string, unknown>;
    tipo: 'electrico' | 'gas';
    comercializadoraData?: Record<string, unknown> | null;
}

const ModalPrecios: React.FC<ModalPreciosProps> = ({
    show,
    onClose,
    onSelect,
    title,
    rowData,
    tipo,
    comercializadoraData,
}) => {
    const [ventanaOptions, setVentanaOptions] = useState<VentanaOption[]>([]);
    const [responseProvider, setResponseProvider] = useState<string>('');
    const [isLoading, setIsLoading] = useState(false);

    const servicioIntegracion = useMemo(() => {
        const raw = comercializadoraData?.Servicio_Integracion
            ?? comercializadoraData?.servicio_integracion;
        return raw ? String(raw).toLowerCase() : '';
    }, [comercializadoraData]);

    const isAdx = isAdxVentanaProvider(responseProvider, servicioIntegracion);
    const subtarifa = String(rowData?.subtarifa || rowData?.anexoNombre || '').trim();

    const buscarVentanasPrecios = () => {
        if (!servicioIntegracion) {
            setVentanaOptions([]);
            setIsLoading(false);
            return;
        }

        setIsLoading(true);
        const tipPreFila = tipoContratoDesdeTipoprecio(rowData?.tipoprecio);

        let params: Record<string, unknown> = {};
        if (tipo === 'electrico') {
            params = {
                gama: rowData.codigoServicioProducto,
                tipo_contrato: tipPreFila,
                tipo_tarifas: 'luz',
                tarifa_luz: rowData.tarifa || rowData.nombreTarifa,
                tipo_contrato_gas: '',
                servicio: servicioIntegracion,
                filtro: rowData.nombreTarifa,
                subtarifa,
            };
        } else {
            params = {
                gama: rowData.codigoServicioProducto,
                tipo_contrato: '',
                tipo_tarifas: 'gas',
                tarifa_gas: '',
                tipo_contrato_gas: tipPreFila,
                servicio: servicioIntegracion,
                filtro: rowData.nombreTarifa,
                subtarifa,
            };
        }

        const url = window.route ? window.route('tarifas.integracion') : '/tarifas/integracion';

        axios.post(url, params)
            .then((res) => {
                setResponseProvider(res.data?.provider || servicioIntegracion);
                setVentanaOptions(res.data?.data || []);
            })
            .catch(() => {
                setVentanaOptions([]);
                setResponseProvider('');
            })
            .finally(() => setIsLoading(false));
    };

    useEffect(() => {
        if (show) {
            buscarVentanasPrecios();
        }
    }, [show]);

    const handleSeleccionarVentana = async (op: VentanaOption) => {
        const result = await Swal.fire({
            title: 'Ventana de precios',
            text: '¿Quieres actualizar las fechas actuales con las de la ventana?',
            icon: 'question',
            showDenyButton: true,
            confirmButtonText: 'Sí',
            denyButtonText: 'No',
        });
        if (result.isDismissed) {
            return;
        }
        onSelect(ventanaOptionToSelection(op, result.isConfirmed === true));
    };

    const formatNum = (v: unknown) => {
        const n = Number(v);
        return Number.isFinite(n) ? n.toFixed(4) : '—';
    };

    const rowKey = (op: VentanaOption, index: number) =>
        op.TarifaCUPS || op.nombre || `ventana-${index}`;

    return (
        <Modal
            show={show}
            onHide={onClose}
            size={isAdx ? 'xl' : 'lg'}
            centered
            scrollable
            contentClassName={estilosFoco.contenedorAccesibleContratos}
        >
            <Modal.Header closeButton>
                <Modal.Title>{title || 'Seleccionar ventana de precios'}</Modal.Title>
            </Modal.Header>
            <Modal.Body style={{ maxHeight: '70vh', overflowY: 'auto' }}>
                {isLoading ? (
                    <div className="text-center p-4">
                        <Spinner animation="border" role="status">
                            <span className="visually-hidden">Cargando...</span>
                        </Spinner>
                        <p className="mt-2">Buscando ventanas de precios...</p>
                    </div>
                ) : ventanaOptions.length === 0 ? (
                    <div className="text-center p-4">
                        <p>No se encontraron ventanas de precios para los criterios seleccionados.</p>
                    </div>
                ) : isAdx ? (
                    <Table striped bordered hover responsive size="sm">
                        <thead>
                            <tr>
                                <th>Nombre</th>
                                <th>Producto</th>
                                <th>Versión</th>
                                <th>Gama</th>
                                <th>Tipo</th>
                                <th>Tarifa</th>
                                <th>Subtarifa</th>
                                <th>GdO</th>
                                <th>V. Inicio</th>
                                <th>V. Fin</th>
                                <th>P1</th>
                                <th>P2</th>
                                <th>E1</th>
                                <th>E2</th>
                                <th>Acción</th>
                            </tr>
                        </thead>
                        <tbody>
                            {ventanaOptions.map((op, index) => (
                                <tr key={rowKey(op, index)}>
                                    <td>{op.nombre || op.TarifaCUPS}</td>
                                    <td>{op.productCode || '—'}</td>
                                    <td>{op.version || '—'}</td>
                                    <td>{op.gama || '—'}</td>
                                    <td>{op.tipoContrato || '—'}</td>
                                    <td>{op.tarifa || '—'}</td>
                                    <td>{op.subtarifa || '—'}</td>
                                    <td>{op.GdO || '—'}</td>
                                    <td>{op.ventanaInicio || op.FechaInicioPoliza || '—'}</td>
                                    <td>{op.ventanaFin || op.FechaFinalPoliza || '—'}</td>
                                    <td>{formatNum(op.PrecioP1)}</td>
                                    <td>{formatNum(op.PrecioP2)}</td>
                                    <td>{formatNum(op.PrecioE1)}</td>
                                    <td>{formatNum(op.PrecioE2)}</td>
                                    <td>
                                        <Button
                                            variant="primary"
                                            size="sm"
                                            onClick={() => void handleSeleccionarVentana(op)}
                                        >
                                            Seleccionar
                                        </Button>
                                    </td>
                                </tr>
                            ))}
                        </tbody>
                    </Table>
                ) : (
                    <Table striped bordered hover responsive>
                        <thead>
                            <tr>
                                <th>Código Tarifa</th>
                                <th>Fecha Inicio</th>
                                <th>Fecha Fin</th>
                                <th>Acción</th>
                            </tr>
                        </thead>
                        <tbody>
                            {ventanaOptions.map((op, index) => (
                                <tr key={rowKey(op, index)}>
                                    <td>{op.TarifaCUPS}</td>
                                    <td>{op.FechaInicioPoliza}</td>
                                    <td>{op.FechaFinalPoliza}</td>
                                    <td>
                                        <Button
                                            variant="primary"
                                            size="sm"
                                            onClick={() => void handleSeleccionarVentana(op)}
                                        >
                                            Seleccionar
                                        </Button>
                                    </td>
                                </tr>
                            ))}
                        </tbody>
                    </Table>
                )}
            </Modal.Body>
            <Modal.Footer>
                <Button variant="secondary" onClick={onClose}>
                    Cerrar
                </Button>
            </Modal.Footer>
        </Modal>
    );
};

export default ModalPrecios;
