import React, { useState, useEffect, useMemo } from 'react';
import {
    Modal,
    Button,
    Alert,
    Spinner,
    ProgressBar,
    Pagination,
    Form,
} from 'react-bootstrap';
import axios from 'axios';
import ProcessIntegrationTable from './ProcessHistoryTables/ProcessIntegrationTable';
import OkCommercialTable from './ProcessHistoryTables/OkCommercialTable';
import CargaGlobalAudaxTable from './ProcessHistoryTables/CargaGlobalAudaxTable';
import { isIntegracionRowProcessed, isOkCommercialRowProcessed } from './processHistoryStatus';

interface ProcessHistory {
    id: number;
    numero_proceso: string;
    tipo_proceso: number;
    operacion: any;
    respuesta: any;
    usuario_id: number | null;
    usuario_nombre: string;
    fecha_operacion: string;
    created_at: string;
    updated_at: string;
}

interface ProcessHistoryModalProps {
    show: boolean;
    onHide: () => void;
    numeroProceso: string;
    tipoProceso?: number; // 1 = Integración, 2 = OK Comercial
}

/** Porcentaje procesados/total con bandas de color (texto y barra). */
function getRegistroProgressTheme(procesados: number, total: number): {
    pct: number;
    textColor: string;
    barBg: string;
} {
    if (total <= 0) {
        return { pct: 0, textColor: '#dc3545', barBg: '#dc3545' };
    }
    const raw = (procesados / total) * 100;
    const pct = Math.min(100, Math.max(0, Math.round(raw)));

    if (pct === 100) {
        return { pct, textColor: '#198754', barBg: '#198754' };
    }
    if (pct >= 75) {
        return { pct, textColor: '#0d6efd', barBg: '#0d6efd' };
    }
    if (pct >= 50) {
        return { pct, textColor: '#fd7e14', barBg: '#fd7e14' };
    }
    if (pct >= 25) {
        return { pct, textColor: '#b8860b', barBg: '#ffc107' };
    }
    return { pct, textColor: '#dc3545', barBg: '#dc3545' };
}

const PAGE_SIZE_OPTIONS = [15, 25, 50, 100, 150, 200, 500] as const;

/** Números de página con elipsis para muchas páginas. */
function buildPaginationItems(currentPage: number, totalPages: number): (number | 'ellipsis')[] {
    if (totalPages <= 1) {
        return [1];
    }
    if (totalPages <= 9) {
        return Array.from({ length: totalPages }, (_, i) => i + 1);
    }
    const set = new Set<number>([1, totalPages, currentPage - 1, currentPage, currentPage + 1]);
    const sorted = [...set].filter((p) => p >= 1 && p <= totalPages).sort((a, b) => a - b);
    const out: (number | 'ellipsis')[] = [];
    for (let i = 0; i < sorted.length; i++) {
        const p = sorted[i]!;
        if (i > 0) {
            const prev = sorted[i - 1]!;
            if (p - prev > 1) {
                out.push('ellipsis');
            }
        }
        out.push(p);
    }
    return out;
}

const ProcessHistoryModal: React.FC<ProcessHistoryModalProps> = ({
    show,
    onHide,
    numeroProceso,
    tipoProceso = 1, // Default a tipo 1 (Integración)
}) => {
    const [histories, setHistories] = useState<ProcessHistory[]>([]);
    const [loading, setLoading] = useState<boolean>(false);
    const [error, setError] = useState<string | null>(null);
    const [pageSize, setPageSize] = useState<number>(15);
    const [currentPage, setCurrentPage] = useState<number>(1);

    useEffect(() => {
        if (show && numeroProceso) {
            setCurrentPage(1);
            void fetchHistories();
        }
    }, [show, numeroProceso, tipoProceso]);

    useEffect(() => {
        const totalPages = Math.max(1, Math.ceil(histories.length / Math.max(1, pageSize)));
        setCurrentPage((p) => Math.min(Math.max(1, p), totalPages));
    }, [histories.length, pageSize]);

    const fetchHistories = async () => {
        setLoading(true);
        setError(null);

        try {
            const response = await axios.get('/process-histories', {
                params: {
                    numero_proceso: numeroProceso,
                    tipo_proceso: tipoProceso
                },
            });

            if (response.data.success) {
                setHistories(response.data.data);
            } else {
                setError('No se pudieron cargar los resultados del proceso');
            }
        } catch (err: any) {
            console.error('Error al cargar historiales:', err);
            setError(err.response?.data?.message || 'Error al cargar los datos');
        } finally {
            setLoading(false);
        }
    };

    const getModalTitle = (): string => {
        switch (tipoProceso) {
            case 1:
                return 'Resultados del Proceso de Integración';
            case 2:
                return 'Resultados del Proceso OK Comercial';
            case 3:
                return 'Resultados de Carga Global Audax';
            case 4:
                return 'Resultados del envío de documentación';
            default:
                return 'Resultados del Proceso';
        }
    };

    const getModalIcon = (): string => {
        switch (tipoProceso) {
            case 1:
                return 'bx-list-ul';
            case 2:
                return 'bx-check-circle';
            case 3:
                return 'bx-file';
            case 4:
                return 'bx-upload';
            default:
                return 'bx-info-circle';
        }
    };

    /** Solo filas con estado "Exitoso" en la tabla cuentan como procesadas; "Desconocido" / "Error" no. */
    const registroSummary = useMemo(() => {
        if (histories.length === 0) {
            return null;
        }
        if (tipoProceso === 1) {
            const total = histories.length;
            const procesados = histories.filter((h) => isIntegracionRowProcessed(h.respuesta)).length;
            return { procesados, total };
        }
        if (tipoProceso === 2) {
            const total = histories.length;
            const procesados = histories.filter((h) => isOkCommercialRowProcessed(h.respuesta)).length;
            return { procesados, total };
        }
        if (tipoProceso === 3) {
            const r = histories[0]?.respuesta as Record<string, unknown> | undefined;
            const summary = (r?.summary as Record<string, unknown> | undefined) ?? {};
            const total = Number(summary.total);
            const procesados = Number(summary.procesados);
            if (Number.isFinite(total) && Number.isFinite(procesados)) {
                return { procesados, total };
            }
        }
        return null;
    }, [histories, tipoProceso]);

    const { paginatedHistories, totalPages, rowOffset, rangeFrom, rangeTo } = useMemo(() => {
        const total = histories.length;
        const paginate = tipoProceso === 1 || tipoProceso === 2 || tipoProceso === 4;
        if (!paginate || total === 0) {
            return {
                paginatedHistories: histories,
                totalPages: 1,
                rowOffset: 0,
                rangeFrom: 0,
                rangeTo: 0,
            };
        }
        const ps = Math.max(1, pageSize);
        const tp = Math.max(1, Math.ceil(total / ps));
        const page = Math.min(Math.max(1, currentPage), tp);
        const start = (page - 1) * ps;
        const slice = histories.slice(start, start + ps);
        return {
            paginatedHistories: slice,
            totalPages: tp,
            rowOffset: start,
            rangeFrom: total === 0 ? 0 : start + 1,
            rangeTo: start + slice.length,
        };
    }, [histories, pageSize, currentPage, tipoProceso]);

    const paginationItems = useMemo(
        () =>
            tipoProceso === 1 || tipoProceso === 2 || tipoProceso === 4
                ? buildPaginationItems(currentPage, totalPages)
                : [],
        [tipoProceso, currentPage, totalPages]
    );

    return (
        <Modal show={show} onHide={onHide} size="xl" centered>
            <Modal.Header closeButton className="bg-success text-white">
                <Modal.Title>
                    <i className={`bx ${getModalIcon()} me-2`}></i>
                    {getModalTitle()}
                </Modal.Title>
            </Modal.Header>
            <Modal.Body>
                {loading ? (
                    <div className="text-center py-5">
                        <Spinner animation="border" variant="success" />
                        <p className="mt-3 text-muted">Cargando resultados...</p>
                    </div>
                ) : error ? (
                    <Alert variant="danger">
                        <i className="bx bx-error-circle me-2"></i>
                        {error}
                    </Alert>
                ) : histories.length === 0 ? (
                    <Alert variant="info">
                        <i className="bx bx-info-circle me-2"></i>
                        No se encontraron registros para este proceso
                    </Alert>
                ) : (
                    <>
                        {registroSummary != null && (() => {
                            const { procesados, total } = registroSummary;
                            const theme = getRegistroProgressTheme(procesados, total);
                            return (
                                <div className="text-center mb-4 border-bottom pb-3">
                                    <p
                                        className="fs-4 fw-semibold mb-2"
                                        style={{ color: theme.textColor }}
                                    >
                                        Se procesaron {procesados} de {total} registros ({theme.pct}%)
                                    </p>
                                    <div className="px-md-5 px-2">
                                        <ProgressBar
                                            className="shadow-sm"
                                            style={{ height: '1.35rem', backgroundColor: '#e9ecef' }}
                                        >
                                            <ProgressBar
                                                now={theme.pct}
                                                max={100}
                                                key="fill"
                                                style={{ backgroundColor: theme.barBg }}
                                                label={`${theme.pct}%`}
                                            />
                                        </ProgressBar>
                                    </div>
                                </div>
                            );
                        })()}
                        <div className="mb-3">
                            <p className="text-muted mb-1">
                                <strong>Número de Proceso:</strong> {numeroProceso}
                            </p>
                            <p className="text-muted mb-1">
                                <strong>Total de Operaciones:</strong> {histories.length}
                            </p>
                            {histories[0] && (
                                <p className="text-muted mb-0">
                                    <strong>Ejecutado por:</strong> {histories[0].usuario_nombre}
                                </p>
                            )}
                        </div>

                        {(tipoProceso === 1 || tipoProceso === 2 || tipoProceso === 4) && (
                            <div className="d-flex flex-column gap-2" style={{ minHeight: 0 }}>
                                <div className="d-flex flex-column flex-md-row flex-wrap align-items-stretch align-items-md-center justify-content-between gap-2 px-1">
                                    <small className="text-muted text-center text-md-start">
                                        {histories.length > 0 ? (
                                            <>
                                                Mostrando <strong>{rangeFrom}</strong>–<strong>{rangeTo}</strong> de{' '}
                                                <strong>{histories.length}</strong>
                                            </>
                                        ) : null}
                                    </small>
                                    <Form.Group className="mb-0 d-flex flex-column flex-sm-row align-items-sm-center gap-2">
                                        <Form.Label className="small mb-0 text-nowrap">Registros por página</Form.Label>
                                        <Form.Select
                                            size="sm"
                                            className="w-auto"
                                            style={{ minWidth: '5.5rem' }}
                                            value={pageSize}
                                            onChange={(e) => {
                                                setPageSize(Number(e.target.value));
                                                setCurrentPage(1);
                                            }}
                                        >
                                            {PAGE_SIZE_OPTIONS.map((n) => (
                                                <option key={n} value={n}>
                                                    {n}
                                                </option>
                                            ))}
                                        </Form.Select>
                                    </Form.Group>
                                </div>
                                <div
                                    className="overflow-auto border rounded"
                                    style={{ maxHeight: 'min(52vh, 440px)' }}
                                >
                                    {tipoProceso === 1 ? (
                                        <ProcessIntegrationTable
                                            histories={paginatedHistories}
                                            rowOffset={rowOffset}
                                        />
                                    ) : (
                                        <OkCommercialTable
                                            histories={paginatedHistories}
                                            rowOffset={rowOffset}
                                        />
                                    )}
                                </div>
                                {totalPages > 1 && (
                                    <div className="d-flex justify-content-center pt-1 overflow-x-auto">
                                        <Pagination className="mb-0 flex-wrap justify-content-center">
                                            <Pagination.First
                                                disabled={currentPage <= 1}
                                                onClick={() => setCurrentPage(1)}
                                            />
                                            <Pagination.Prev
                                                disabled={currentPage <= 1}
                                                onClick={() => setCurrentPage((p) => Math.max(1, p - 1))}
                                            />
                                            {paginationItems.map((item, idx) =>
                                                item === 'ellipsis' ? (
                                                    <Pagination.Ellipsis key={`ellipsis-${idx}`} disabled />
                                                ) : (
                                                    <Pagination.Item
                                                        key={item}
                                                        active={item === currentPage}
                                                        onClick={() => setCurrentPage(item)}
                                                    >
                                                        {item}
                                                    </Pagination.Item>
                                                )
                                            )}
                                            <Pagination.Next
                                                disabled={currentPage >= totalPages}
                                                onClick={() => setCurrentPage((p) => Math.min(totalPages, p + 1))}
                                            />
                                            <Pagination.Last
                                                disabled={currentPage >= totalPages}
                                                onClick={() => setCurrentPage(totalPages)}
                                            />
                                        </Pagination>
                                    </div>
                                )}
                            </div>
                        )}
                        {tipoProceso === 3 && <CargaGlobalAudaxTable histories={histories} />}
                    </>
                )}
            </Modal.Body>
            <Modal.Footer>
                <Button variant="secondary" onClick={onHide}>
                    Cerrar
                </Button>
                {histories.length > 0 && (
                    <Button variant="success" onClick={fetchHistories} disabled={loading}>
                        <i className="bx bx-refresh me-1"></i>
                        Actualizar
                    </Button>
                )}
            </Modal.Footer>
        </Modal>
    );
};

export default ProcessHistoryModal;
