import { TableVirtual } from "@components/Crud/TableVirtual";
import { IconApp } from "@components/IconApp";
import LinkToStudenFormApp from "@components/LinkToStudenFormApp";
import ModalApp from "@components/ModalApp";
import { DATA as filterStatus } from "@components/Options/students/OptionsStatus";
import { SelectSearchApp } from "@components/SelectSearchApp";
import { StudentStatusIcon } from "@components/StudentStatusIcon";
import { chartColors } from "@helpers/ChartColors";
import { formatMoney } from "@helpers/FormatString";
import { useForm } from "@hooks/useForm";
import {
    startExportPortfolioManagementDetection,
    startGetPortfolioManagementDetection,
} from "@redux/slices/operators/PortfolioManagement";
import { Empty } from "antd";
import dayjs from "dayjs";
import React, { useEffect, useMemo, useState } from "react";
import { Button, Col, Row } from "react-bootstrap";
import { useDispatch, useSelector } from "react-redux";
import AddStudentsToCampaign from "./AddStudentsToCampaign";

const ALL_YEARS = "ALL";
const ALL_MONTHS = "Todos";
const CURRENT_YEAR = dayjs().format("YYYY");
const EMPTY_ARRAY = Object.freeze([]);
const BASE_HEADERS_FALLBACK = [
    "Seleccionar todos",
    "#",
    "Matrícula",
    "Nombre completo",
    "Estatus",
    "Oferta educativa",
    "Adeudo total",
];
const STICKY_COLUMN_STYLES = [
    { left: "0px", width: "56px", minWidth: "56px" },
    { left: "56px", width: "56px", minWidth: "56px" },
    { left: "112px", width: "100px", minWidth: "100px" },
    { left: "212px", width: "220px", minWidth: "220px" },
    { left: "432px", width: "160px", minWidth: "160px" },
    { left: "592px", width: "220px", minWidth: "220px" },
    { left: "812px", width: "160px", minWidth: "160px" },
];

const defaultValues = {
    status_student: [],
    errors: {},
};

export default function TabDetection() {
    const dispatch = useDispatch();

    const { detectionList } = useSelector((state) => state.portfolioManagement);

    const [checkedStudents, setCheckedStudents] = useState({});
    const [checkAll, setCheckAll] = useState(false);
    const [selectedYears, setSelectedYears] = useState([CURRENT_YEAR]);
    const [selectedMonths, setSelectedMonths] = useState([ALL_MONTHS]);
    const [activeMonthYear, setActiveMonthYear] = useState(CURRENT_YEAR);

    const { values, handleInputChange } = useForm(defaultValues);
    const { status_student, errors } = values;

    const studentsWithDebts = detectionList?.students_with_debts ?? EMPTY_ARRAY;
    const selectedStudentStatuses = Array.isArray(status_student)
        ? status_student
        : EMPTY_ARRAY;

    const monthColumns = detectionList?.month_columns ?? EMPTY_ARRAY;
    const isStickyColumn = (index) => index >= 0 && index <= 6;
    const getStickyStyle = (index) => STICKY_COLUMN_STYLES[index] || {};

    const getStudentKey = (student, index) => {
        return (
            student?.academic_record_id ||
            student?.student_number ||
            `row-${index}`
        );
    };

    const getMonthLabel = (column) =>
        String(column?.month || column?.label || "--");

    const yearOptions = useMemo(() => {
        const uniqueYears = Array.from(
            new Set(
                monthColumns
                    .map((column) => column?.year)
                    .filter((year) => Number.isInteger(year)),
            ),
        ).sort((a, b) => b - a);

        return [
            { value: ALL_YEARS, label: "Todos" },
            ...uniqueYears.map((year) => ({
                value: String(year),
                label: String(year),
            })),
        ];
    }, [monthColumns]);

    const availableYearValues = useMemo(() => {
        return yearOptions
            .filter((option) => option.value !== ALL_YEARS)
            .map((option) => option.value);
    }, [yearOptions]);

    const selectedYearsSet = useMemo(
        () => new Set(selectedYears),
        [selectedYears],
    );

    const selectedMonthsSet = useMemo(
        () => new Set(selectedMonths),
        [selectedMonths],
    );

    const hasAllYearsSelected = selectedYearsSet.has(ALL_YEARS);
    const hasAllMonthsSelected = selectedMonthsSet.has(ALL_MONTHS);

    const visibleMonthColumns = useMemo(() => {
        let filteredColumns = monthColumns;

        if (!hasAllYearsSelected) {
            filteredColumns = filteredColumns.filter((column) =>
                selectedYearsSet.has(String(column?.year)),
            );
        }

        if (!hasAllMonthsSelected) {
            filteredColumns = filteredColumns.filter((column) =>
                selectedMonthsSet.has(getMonthLabel(column)),
            );
        }

        return filteredColumns;
    }, [
        monthColumns,
        hasAllYearsSelected,
        hasAllMonthsSelected,
        selectedYearsSet,
        selectedMonthsSet,
    ]);

    const monthOptionsAllowed = useMemo(() => {
        const sourceColumns = hasAllYearsSelected
            ? monthColumns
            : monthColumns.filter((column) =>
                  selectedYearsSet.has(String(column?.year)),
              );

        const uniqueMonths = Array.from(
            new Set(sourceColumns.map((column) => getMonthLabel(column))),
        );

        return [...uniqueMonths, ALL_MONTHS];
    }, [monthColumns, hasAllYearsSelected, selectedYearsSet]);

    const activeMonthYearToShow = useMemo(() => {
        const candidateYears = hasAllYearsSelected
            ? availableYearValues
            : selectedYears.filter((year) => year !== ALL_YEARS);

        if (candidateYears.length === 0) {
            if (availableYearValues.includes(activeMonthYear)) {
                return activeMonthYear;
            }

            if (availableYearValues.includes(CURRENT_YEAR)) {
                return CURRENT_YEAR;
            }

            return availableYearValues[0] || null;
        }

        if (candidateYears.includes(activeMonthYear)) {
            return activeMonthYear;
        }

        return candidateYears[0];
    }, [
        hasAllYearsSelected,
        availableYearValues,
        selectedYears,
        activeMonthYear,
    ]);

    const yearsWithSelectedMonthsSet = useMemo(() => {
        if (hasAllMonthsSelected) {
            return new Set(
                hasAllYearsSelected
                    ? availableYearValues
                    : selectedYears.filter((year) => year !== ALL_YEARS),
            );
        }

        return new Set(
            monthColumns
                .filter((column) =>
                    selectedMonthsSet.has(getMonthLabel(column)),
                )
                .map((column) => String(column?.year)),
        );
    }, [
        hasAllMonthsSelected,
        hasAllYearsSelected,
        availableYearValues,
        selectedYears,
        monthColumns,
        selectedMonthsSet,
    ]);

    const monthOptionsVisible = useMemo(() => {
        if (!activeMonthYearToShow) {
            return [ALL_MONTHS];
        }

        const sourceColumns = monthColumns.filter(
            (column) => String(column?.year) === String(activeMonthYearToShow),
        );

        const uniqueMonths = Array.from(
            new Set(sourceColumns.map((column) => getMonthLabel(column))),
        );

        return [ALL_MONTHS, ...uniqueMonths];
    }, [monthColumns, activeMonthYearToShow]);

    const visibleMonthLabels = useMemo(() => {
        return monthOptionsVisible.filter((month) => month !== ALL_MONTHS);
    }, [monthOptionsVisible]);

    const areAllVisibleMonthsSelected = useMemo(() => {
        if (visibleMonthLabels.length === 0) {
            return false;
        }

        if (hasAllMonthsSelected) {
            return true;
        }

        return visibleMonthLabels.every((month) =>
            selectedMonthsSet.has(month),
        );
    }, [visibleMonthLabels, hasAllMonthsSelected, selectedMonthsSet]);

    const baseTableHeaders = useMemo(() => {
        const apiHeaders = Array.isArray(detectionList?.headers)
            ? detectionList.headers
            : EMPTY_ARRAY;

        if (apiHeaders.length === 0) {
            return BASE_HEADERS_FALLBACK;
        }

        const totalMonthColumns = monthColumns.length;
        const baseHeadersLength = Math.max(
            apiHeaders.length - totalMonthColumns,
            0,
        );

        if (baseHeadersLength === 0) {
            return BASE_HEADERS_FALLBACK;
        }

        return apiHeaders.slice(0, baseHeadersLength);
    }, [detectionList?.headers, monthColumns]);

    const tableHeaders = useMemo(() => {
        return [
            ...baseTableHeaders,
            ...visibleMonthColumns.map((column) => column?.label || "--"),
        ];
    }, [baseTableHeaders, visibleMonthColumns]);

    const visibleMonthColumnKeys = useMemo(() => {
        return visibleMonthColumns
            .map((column) => String(column?.key || "").trim())
            .filter(Boolean);
    }, [visibleMonthColumns]);

    const filteredStudentsWithDebts = useMemo(() => {
        const selectedStatusesSet = new Set(
            selectedStudentStatuses.map((status) =>
                String(status?.value ?? status ?? "")
                    .trim()
                    .toUpperCase(),
            ),
        );

        const studentsFilteredByStatus =
            selectedStudentStatuses.length === 0
                ? studentsWithDebts
                : studentsWithDebts.filter((student) =>
                      selectedStatusesSet.has(
                          String(student?.student_status || "")
                              .trim()
                              .toUpperCase(),
                      ),
                  );

        const shouldApplyPeriodFilter =
            !hasAllYearsSelected || !hasAllMonthsSelected;

        if (!shouldApplyPeriodFilter) {
            return studentsFilteredByStatus;
        }

        if (visibleMonthColumnKeys.length === 0) {
            return [];
        }

        return studentsFilteredByStatus.filter((student) => {
            return visibleMonthColumnKeys.some((columnKey) => {
                const amount = Number(student?.months_map?.[columnKey] || 0);

                return amount > 0;
            });
        });
    }, [
        studentsWithDebts,
        selectedStudentStatuses,
        hasAllYearsSelected,
        hasAllMonthsSelected,
        visibleMonthColumnKeys,
    ]);

    const selectableStudentKeys = useMemo(() => {
        return studentsWithDebts.reduce((accumulator, student, index) => {
            if (student?.has_open_cashing_campaign) {
                return accumulator;
            }

            accumulator.push(String(getStudentKey(student, index)));
            return accumulator;
        }, []);
    }, [studentsWithDebts]);

    const visibleSelectableStudentKeys = useMemo(() => {
        return filteredStudentsWithDebts.reduce(
            (accumulator, student, index) => {
                if (student?.has_open_cashing_campaign) {
                    return accumulator;
                }

                accumulator.push(String(getStudentKey(student, index)));
                return accumulator;
            },
            [],
        );
    }, [filteredStudentsWithDebts]);

    //* Total de adeudos de los alumnos que se encuentran filtrados (visibles en la tabla)
    const totalDebtsByFilteredStudentsWithDebts = useMemo(() => {
        let totaldebts = 0;

        if (filteredStudentsWithDebts?.length > 0) {
            filteredStudentsWithDebts.forEach((item) => {
                if (item?.total_debt) {
                    totaldebts = totaldebts + item.total_debt;
                }
            });
        }

        return totaldebts;
    }, [filteredStudentsWithDebts]);

    const selectableStudentKeySet = useMemo(() => {
        return new Set(selectableStudentKeys);
    }, [selectableStudentKeys]);

    const hasSelectedStudents = useMemo(() => {
        return selectableStudentKeys.some((studentKey) =>
            Boolean(checkedStudents[studentKey]),
        );
    }, [checkedStudents, selectableStudentKeys]);

    //* Número de alumnos checkeados
    const selectedStudentsCount = useMemo(() => {
        return Object.entries(checkedStudents)
            .filter(
                ([academic_record_id, status]) =>
                    status &&
                    selectableStudentKeySet.has(String(academic_record_id)),
            )
            ?.map((item) => item[0])?.length;
    }, [checkedStudents, selectableStudentKeySet]);

    useEffect(() => {
        getData();
    }, []);

    useEffect(() => {
        const initialCheckedStates = studentsWithDebts.reduce(
            (accumulator, student, index) => {
                const studentKey = getStudentKey(student, index);

                accumulator[studentKey] = false;
                return accumulator;
            },
            {},
        );

        setCheckedStudents(initialCheckedStates);
        setCheckAll(false);
    }, [studentsWithDebts]);

    useEffect(() => {
        if (visibleSelectableStudentKeys.length === 0) {
            setCheckAll(false);
            return;
        }

        const allChecked = visibleSelectableStudentKeys.every((studentKey) =>
            Boolean(checkedStudents[studentKey]),
        );

        setCheckAll(allChecked);
    }, [checkedStudents, visibleSelectableStudentKeys]);

    useEffect(() => {
        if (monthColumns.length === 0) {
            return;
        }

        const allowedYears = new Set(yearOptions.map((option) => option.value));
        const validYears = selectedYears.filter((year) =>
            allowedYears.has(year),
        );

        if (selectedYears.length === 0) {
            return;
        }

        if (validYears.length === 0) {
            if (allowedYears.has(CURRENT_YEAR)) {
                setSelectedYears([CURRENT_YEAR]);
                return;
            }

            setSelectedYears([ALL_YEARS]);
            return;
        }

        if (validYears.includes(ALL_YEARS) && validYears.length > 1) {
            setSelectedYears([ALL_YEARS]);
            return;
        }

        if (validYears.length !== selectedYears.length) {
            setSelectedYears(validYears);
        }
    }, [yearOptions, selectedYears, monthColumns]);

    useEffect(() => {
        if (availableYearValues.length === 0) {
            return;
        }

        if (availableYearValues.includes(activeMonthYear)) {
            return;
        }

        if (availableYearValues.includes(CURRENT_YEAR)) {
            setActiveMonthYear(CURRENT_YEAR);
            return;
        }

        setActiveMonthYear(availableYearValues[0]);
    }, [availableYearValues, activeMonthYear]);

    useEffect(() => {
        const allowedMonths = new Set(monthOptionsAllowed);
        const validMonths = selectedMonths.filter((month) =>
            allowedMonths.has(month),
        );

        if (validMonths.length === 0) {
            if (selectedMonths.length !== 0) {
                setSelectedMonths([]);
            }
            return;
        }

        if (validMonths.includes(ALL_MONTHS) && validMonths.length > 1) {
            setSelectedMonths([ALL_MONTHS]);
            return;
        }

        if (validMonths.length !== selectedMonths.length) {
            setSelectedMonths(validMonths);
        }
    }, [monthOptionsAllowed, selectedMonths]);

    const getData = () => {
        dispatch(startGetPortfolioManagementDetection());
    };

    const handleCheck = (checked, studentKey) => {
        setCheckedStudents((prev) => ({ ...prev, [studentKey]: checked }));
    };

    const handleCheckAll = (checked) => {
        setCheckedStudents((prev) => {
            const updatedChecks = { ...prev };

            visibleSelectableStudentKeys.forEach((studentKey) => {
                updatedChecks[studentKey] = checked;
            });

            return updatedChecks;
        });
    };

    return (
        <div>
            {detectionList ? (
                <div className="mt-2 mt-md-3">
                    <Row className="g-3 text-center d-flex justify-content-center">
                        <Col xs={12} sm={6} md={6} lg={6} xl={6} xxl={6}>
                            <div
                                className="shadow-sm rounded-4 px-3 py-2 text-center border"
                                style={{
                                    background:
                                        "linear-gradient(135deg, #fff5e8 0%, #fffdf7 100%)",
                                    borderColor: "#ffd8a8",
                                    color: "#8a4a00",
                                }}
                            >
                                <p
                                    className="fw-semibold text-uppercase mb-1"
                                    style={{
                                        letterSpacing: "0.4px",
                                        fontSize: "12px",
                                    }}
                                >
                                    Alumnos con adeudo
                                </p>
                                <span className="fs-5 fw-bold m-0 lh-1 d-flex align-items-center justify-content-center gap-2">
                                    <IconApp
                                        iconClassName="fa-solid fa-user-graduate"
                                        color={chartColors.orange.main}
                                    />
                                    {Number(filteredStudentsWithDebts?.length)}
                                    {/* {Number(
                                        detectionList?.breakdown?.total
                                            ?.students || 0,
                                    ).toLocaleString("es-MX")} */}
                                </span>
                            </div>
                        </Col>

                        <Col xs={12} sm={6} md={6} lg={6} xl={6} xxl={6}>
                            <div
                                className="shadow-sm rounded-4 px-3 py-2 text-center border"
                                style={{
                                    background:
                                        "linear-gradient(135deg, #ffeaea 0%, #fff8f8 100%)",
                                    borderColor: "#ffc4c4",
                                    color: "#8f1f1f",
                                }}
                            >
                                <p
                                    className="fw-semibold text-uppercase mb-1"
                                    style={{
                                        letterSpacing: "0.4px",
                                        fontSize: "12px",
                                    }}
                                >
                                    Adeudos totales
                                </p>
                                <span className="fs-5 fw-bold m-0 lh-1 d-flex align-items-center justify-content-center gap-2">
                                    <IconApp
                                        iconClassName="fa-solid fa-file-invoice-dollar"
                                        color={chartColors.red.main}
                                    />
                                    {formatMoney(
                                        totalDebtsByFilteredStudentsWithDebts ||
                                            0,
                                    )}
                                    {/* {formatMoney(
                                        detectionList?.breakdown?.total
                                            ?.debts || 0,
                                    )} */}
                                </span>
                            </div>
                        </Col>
                    </Row>

                    <div
                        className="mt-3 p-2 p-md-3 rounded-4 border bg-white shadow-sm"
                        style={{
                            background:
                                "linear-gradient(135deg, #ffffff 0%, #f9fbff 100%)",
                            borderColor: "#e0e7ff",
                        }}
                    >
                        <Row className="g-2 g-md-5">
                            <Col xs={12} lg={12} xl={3} xxl={2}>
                                <SelectSearchApp
                                    title="Estatus del alumno"
                                    placeholder="Filtrar por estatus de alumno"
                                    multiple
                                    name="status_student"
                                    value={status_student}
                                    onChange={handleInputChange}
                                    options={filterStatus}
                                    errorText={
                                        errors.status_student &&
                                        errors.status_student[0]
                                    }
                                />
                            </Col>

                            <Col xs={12} lg={12} xl={9} xxl={10}>
                                {yearOptions.length > 1 ? (
                                    <div className="d-flex flex-column gap-3 h-100">
                                        <div className="d-flex align-items-center gap-2 flex-wrap">
                                            <span
                                                className="text-muted fw-bold text-uppercase"
                                                style={{
                                                    fontSize:
                                                        "clamp(10px, 1.9vw, 11px)",
                                                    letterSpacing: "0.5px",
                                                }}
                                            >
                                                <IconApp iconClassName="fas fa-calendar-alt me-1" />
                                                Año de corte:
                                            </span>

                                            <div className="d-flex flex-wrap gap-2">
                                                {yearOptions.map((option) => {
                                                    const isAllYearsOption =
                                                        option.value ===
                                                        ALL_YEARS;
                                                    const isYearSelected =
                                                        isAllYearsOption
                                                            ? hasAllYearsSelected
                                                            : hasAllYearsSelected ||
                                                              selectedYearsSet.has(
                                                                  option.value,
                                                              );
                                                    const isActiveYear =
                                                        !isAllYearsOption &&
                                                        activeMonthYearToShow ===
                                                            option.value;
                                                    const hasSelectedMonthsForYear =
                                                        isAllYearsOption
                                                            ? hasAllMonthsSelected
                                                            : hasAllMonthsSelected ||
                                                              yearsWithSelectedMonthsSet.has(
                                                                  option.value,
                                                              );
                                                    const shouldUsePrimaryStyle =
                                                        isYearSelected &&
                                                        hasSelectedMonthsForYear;
                                                    const isActiveYearWithSelectedMonths =
                                                        shouldUsePrimaryStyle &&
                                                        isActiveYear;

                                                    return (
                                                        <button
                                                            key={`detection-year-tab-${option.value}`}
                                                            type="button"
                                                            className={`btn btn-sm rounded-pill px-2 px-md-3 text-size-10 transition-app ${
                                                                shouldUsePrimaryStyle
                                                                    ? "btn-primary shadow-sm"
                                                                    : "btn-light"
                                                            }`}
                                                            style={{
                                                                fontWeight:
                                                                    shouldUsePrimaryStyle ||
                                                                    isActiveYear
                                                                        ? "600"
                                                                        : isYearSelected
                                                                          ? "500"
                                                                          : "400",
                                                                backgroundColor:
                                                                    shouldUsePrimaryStyle
                                                                        ? null
                                                                        : isActiveYear
                                                                          ? "#eff6ff"
                                                                          : "#fbfdff",
                                                                color: shouldUsePrimaryStyle
                                                                    ? null
                                                                    : isActiveYear
                                                                      ? "#1d4ed8"
                                                                      : isYearSelected
                                                                        ? "#475569"
                                                                        : null,
                                                                border: `1px solid ${
                                                                    isActiveYearWithSelectedMonths
                                                                        ? "#dbeafe"
                                                                        : shouldUsePrimaryStyle
                                                                          ? "#a5bdde6b"
                                                                          : isActiveYear
                                                                            ? "#93c5fd"
                                                                            : isYearSelected
                                                                              ? "#cbd5e1"
                                                                              : "#a5bdde6b"
                                                                }`,
                                                                outline:
                                                                    isActiveYearWithSelectedMonths
                                                                        ? "2px solid #93c5fd"
                                                                        : "none",
                                                                outlineOffset:
                                                                    isActiveYearWithSelectedMonths
                                                                        ? "1px"
                                                                        : undefined,
                                                                boxShadow:
                                                                    isActiveYearWithSelectedMonths
                                                                        ? "0 0 0 3px rgba(219, 234, 254, 0.95), 0 6px 14px rgba(37, 99, 235, 0.18)"
                                                                        : !shouldUsePrimaryStyle &&
                                                                            isActiveYear
                                                                          ? "0 0 0 1px rgba(59, 130, 246, 0.08)"
                                                                          : undefined,
                                                                transform:
                                                                    isActiveYearWithSelectedMonths
                                                                        ? "translateY(-1px)"
                                                                        : undefined,
                                                            }}
                                                            onClick={() => {
                                                                if (
                                                                    option.value ===
                                                                    ALL_YEARS
                                                                ) {
                                                                    if (
                                                                        hasAllYearsSelected
                                                                    ) {
                                                                        setSelectedYears(
                                                                            [],
                                                                        );
                                                                        setSelectedMonths(
                                                                            [],
                                                                        );
                                                                        return;
                                                                    }

                                                                    setSelectedYears(
                                                                        [
                                                                            ALL_YEARS,
                                                                        ],
                                                                    );
                                                                    setSelectedMonths(
                                                                        [
                                                                            ALL_MONTHS,
                                                                        ],
                                                                    );

                                                                    if (
                                                                        availableYearValues.includes(
                                                                            CURRENT_YEAR,
                                                                        )
                                                                    ) {
                                                                        setActiveMonthYear(
                                                                            CURRENT_YEAR,
                                                                        );
                                                                    } else if (
                                                                        availableYearValues.length >
                                                                        0
                                                                    ) {
                                                                        setActiveMonthYear(
                                                                            availableYearValues[0],
                                                                        );
                                                                    }

                                                                    return;
                                                                }

                                                                if (
                                                                    option.value !==
                                                                        ALL_YEARS &&
                                                                    hasAllYearsSelected
                                                                ) {
                                                                    setActiveMonthYear(
                                                                        option.value,
                                                                    );
                                                                    return;
                                                                }

                                                                const alreadySelectedYear =
                                                                    selectedYearsSet.has(
                                                                        option.value,
                                                                    );

                                                                setSelectedYears(
                                                                    (prev) => {
                                                                        const withoutAll =
                                                                            prev.filter(
                                                                                (
                                                                                    item,
                                                                                ) =>
                                                                                    item !==
                                                                                    ALL_YEARS,
                                                                            );
                                                                        const alreadySelected =
                                                                            withoutAll.includes(
                                                                                option.value,
                                                                            );

                                                                        if (
                                                                            alreadySelected
                                                                        ) {
                                                                            return withoutAll;
                                                                        }

                                                                        const next =
                                                                            [
                                                                                ...withoutAll,
                                                                                option.value,
                                                                            ];

                                                                        return next.length >
                                                                            0
                                                                            ? next
                                                                            : [
                                                                                  ALL_YEARS,
                                                                              ];
                                                                    },
                                                                );

                                                                if (
                                                                    option.value !==
                                                                        ALL_YEARS &&
                                                                    !alreadySelectedYear &&
                                                                    selectedMonthsSet.has(
                                                                        ALL_MONTHS,
                                                                    )
                                                                ) {
                                                                    const selectedYearValues =
                                                                        hasAllYearsSelected
                                                                            ? availableYearValues
                                                                            : selectedYears.filter(
                                                                                  (
                                                                                      year,
                                                                                  ) =>
                                                                                      year !==
                                                                                      ALL_YEARS,
                                                                              );

                                                                    const monthsFromCurrentSelection =
                                                                        Array.from(
                                                                            new Set(
                                                                                monthColumns
                                                                                    .filter(
                                                                                        (
                                                                                            column,
                                                                                        ) =>
                                                                                            selectedYearValues.includes(
                                                                                                String(
                                                                                                    column?.year,
                                                                                                ),
                                                                                            ),
                                                                                    )
                                                                                    .map(
                                                                                        (
                                                                                            column,
                                                                                        ) =>
                                                                                            getMonthLabel(
                                                                                                column,
                                                                                            ),
                                                                                    ),
                                                                            ),
                                                                        );

                                                                    setSelectedMonths(
                                                                        monthsFromCurrentSelection,
                                                                    );
                                                                }

                                                                if (
                                                                    option.value !==
                                                                    ALL_YEARS
                                                                ) {
                                                                    setActiveMonthYear(
                                                                        option.value,
                                                                    );
                                                                }
                                                            }}
                                                        >
                                                            {option.label}
                                                        </button>
                                                    );
                                                })}
                                            </div>
                                        </div>

                                        {monthOptionsVisible.length > 1 ? (
                                            <div className="d-flex align-items-center gap-2 flex-wrap pt-2 border-top border-light-blue-1">
                                                <span
                                                    className="text-muted fw-bold text-uppercase mt-2"
                                                    style={{
                                                        fontSize:
                                                            "clamp(10px, 1.9vw, 11px)",
                                                        letterSpacing: "0.5px",
                                                    }}
                                                >
                                                    <IconApp iconClassName="fas fa-clock me-1" />
                                                    Detalle por mes:
                                                </span>

                                                <div className="d-flex flex-wrap gap-1 mt-2">
                                                    {monthOptionsVisible.map(
                                                        (month) => (
                                                            <button
                                                                key={`detection-month-tab-${month}`}
                                                                type="button"
                                                                className={`btn btn-sm rounded-pill px-2 px-md-3 mb-1 text-size-10 transition-app ${
                                                                    month ===
                                                                    ALL_MONTHS
                                                                        ? areAllVisibleMonthsSelected
                                                                            ? "btn-primary shadow-sm"
                                                                            : "btn-light"
                                                                        : hasAllMonthsSelected
                                                                          ? "btn-primary shadow-sm"
                                                                          : selectedMonthsSet.has(
                                                                                  month,
                                                                              )
                                                                            ? "btn-primary shadow-sm"
                                                                            : "btn-light"
                                                                }`}
                                                                style={{
                                                                    fontWeight:
                                                                        month ===
                                                                        ALL_MONTHS
                                                                            ? areAllVisibleMonthsSelected
                                                                                ? "600"
                                                                                : "400"
                                                                            : hasAllMonthsSelected
                                                                              ? month ===
                                                                                ALL_MONTHS
                                                                                  ? "600"
                                                                                  : "400"
                                                                              : selectedMonthsSet.has(
                                                                                      month,
                                                                                  )
                                                                                ? "600"
                                                                                : "400",
                                                                    backgroundColor:
                                                                        month ===
                                                                        ALL_MONTHS
                                                                            ? areAllVisibleMonthsSelected
                                                                                ? null
                                                                                : "#fbfdff"
                                                                            : (
                                                                                    hasAllMonthsSelected
                                                                                        ? month ===
                                                                                          ALL_MONTHS
                                                                                        : selectedMonthsSet.has(
                                                                                              month,
                                                                                          )
                                                                                )
                                                                              ? null
                                                                              : "#fbfdff",
                                                                    border: "1px solid #a5bdde6b",
                                                                }}
                                                                onClick={() => {
                                                                    if (
                                                                        selectedYears.length ===
                                                                            0 &&
                                                                        activeMonthYearToShow
                                                                    ) {
                                                                        setSelectedYears(
                                                                            [
                                                                                activeMonthYearToShow,
                                                                            ],
                                                                        );
                                                                    }

                                                                    setSelectedMonths(
                                                                        (
                                                                            prev,
                                                                        ) => {
                                                                            if (
                                                                                month ===
                                                                                ALL_MONTHS
                                                                            ) {
                                                                                const expandedSelection =
                                                                                    prev.includes(
                                                                                        ALL_MONTHS,
                                                                                    )
                                                                                        ? monthOptionsAllowed.filter(
                                                                                              (
                                                                                                  item,
                                                                                              ) =>
                                                                                                  item !==
                                                                                                  ALL_MONTHS,
                                                                                          )
                                                                                        : prev.filter(
                                                                                              (
                                                                                                  item,
                                                                                              ) =>
                                                                                                  item !==
                                                                                                  ALL_MONTHS,
                                                                                          );

                                                                                const allVisibleSelected =
                                                                                    visibleMonthLabels.length >
                                                                                        0 &&
                                                                                    visibleMonthLabels.every(
                                                                                        (
                                                                                            visibleMonth,
                                                                                        ) =>
                                                                                            expandedSelection.includes(
                                                                                                visibleMonth,
                                                                                            ),
                                                                                    );

                                                                                if (
                                                                                    allVisibleSelected
                                                                                ) {
                                                                                    return expandedSelection.filter(
                                                                                        (
                                                                                            item,
                                                                                        ) =>
                                                                                            !visibleMonthLabels.includes(
                                                                                                item,
                                                                                            ),
                                                                                    );
                                                                                }

                                                                                return Array.from(
                                                                                    new Set(
                                                                                        [
                                                                                            ...expandedSelection,
                                                                                            ...visibleMonthLabels,
                                                                                        ],
                                                                                    ),
                                                                                );
                                                                            }

                                                                            const expandedSelection =
                                                                                prev.includes(
                                                                                    ALL_MONTHS,
                                                                                )
                                                                                    ? monthOptionsAllowed.filter(
                                                                                          (
                                                                                              item,
                                                                                          ) =>
                                                                                              item !==
                                                                                              ALL_MONTHS,
                                                                                      )
                                                                                    : prev;

                                                                            const withoutAll =
                                                                                expandedSelection.filter(
                                                                                    (
                                                                                        item,
                                                                                    ) =>
                                                                                        item !==
                                                                                        ALL_MONTHS,
                                                                                );
                                                                            const alreadySelected =
                                                                                withoutAll.includes(
                                                                                    month,
                                                                                );

                                                                            const next =
                                                                                alreadySelected
                                                                                    ? withoutAll.filter(
                                                                                          (
                                                                                              item,
                                                                                          ) =>
                                                                                              item !==
                                                                                              month,
                                                                                      )
                                                                                    : [
                                                                                          ...withoutAll,
                                                                                          month,
                                                                                      ];

                                                                            return next.length >
                                                                                0
                                                                                ? next
                                                                                : [];
                                                                        },
                                                                    );
                                                                }}
                                                            >
                                                                {month}
                                                            </button>
                                                        ),
                                                    )}
                                                </div>
                                            </div>
                                        ) : null}
                                    </div>
                                ) : null}
                            </Col>
                        </Row>
                    </div>

                    <div className="mt-3">
                        <div className="d-flex flex-column flex-md-row justify-content-center justify-content-md-end align-items-stretch align-items-md-center gap-2">
                            <div
                                className="px-3 py-1 rounded-pill border d-inline-flex align-items-center justify-content-center me-md-2"
                                style={{
                                    borderColor: "#c7d2fe",
                                    backgroundColor: "#eef2ff",
                                    color: "#3730a3",
                                    fontWeight: 600,
                                }}
                            >
                                <IconApp iconClassName="fas fa-user-check me-1" />
                                <span className="text-size-10">
                                    {`Seleccionados: ${selectedStudentsCount}`}
                                </span>
                            </div>

                            <div className="d-flex flex-column flex-sm-row justify-content-center justify-content-md-end align-items-stretch gap-2">
                                {!hasSelectedStudents ? (
                                    <Button
                                        className="btn-app btn-app-info"
                                        disabled
                                    >
                                        <span>
                                            Añadir seleccionados a campaña
                                        </span>
                                        <IconApp iconClassName="fas fa-user-tag ms-2" />
                                    </Button>
                                ) : (
                                    <ModalApp
                                        titleModal={"Añadir alumnos a campaña"}
                                        backdrop="static"
                                        keyboard={false}
                                        size="md"
                                        Action={() => (
                                            <Button className="btn-app btn-app-info">
                                                <span>
                                                    Añadir seleccionados a
                                                    campaña
                                                </span>
                                                <IconApp iconClassName="fas fa-user-tag ms-2" />
                                            </Button>
                                        )}
                                    >
                                        <AddStudentsToCampaign
                                            academic_record_ids={Object.entries(
                                                checkedStudents,
                                            )
                                                .filter(
                                                    ([
                                                        academic_record_id,
                                                        status,
                                                    ]) =>
                                                        status &&
                                                        selectableStudentKeySet.has(
                                                            String(
                                                                academic_record_id,
                                                            ),
                                                        ),
                                                )
                                                ?.map((item) => item[0])}
                                            callback={getData}
                                        />
                                    </ModalApp>
                                )}

                                <Button
                                    className="btn-app-green-with-hover"
                                    onClick={() =>
                                        dispatch(
                                            startExportPortfolioManagementDetection(
                                                {
                                                    months: visibleMonthColumns.map(
                                                        (column) =>
                                                            column?.label ||
                                                            "--",
                                                    ),
                                                    status_student:
                                                        status_student,
                                                },
                                            ),
                                        )
                                    }
                                >
                                    <span>Exportar a Excel</span>
                                    <IconApp iconClassName="fas fa-file-excel ms-2" />
                                </Button>

                                <Button
                                    className="btn-app btn-app-secondary"
                                    onClick={getData}
                                >
                                    <span>Refrescar</span>
                                    <IconApp iconClassName="fas fa-refresh ms-2" />
                                </Button>
                            </div>
                        </div>
                    </div>

                    <TableVirtual
                        tableId="portfolio-management-detection-list"
                        classNameTrHeader="bg-blue"
                        hasActions={false}
                        data={filteredStudentsWithDebts}
                        maxHeight={470}
                        striped
                        hover
                        animateRows={false}
                        stickyLeftCount={2}
                        placeholderSearch={"Buscar por matrícula o nombre"}
                        searchKeys={["student_number", "student_full_name"]}
                        renderHeaders={tableHeaders.map((header, index) => (
                            <React.Fragment key={`${header}-${index}`}>
                                {index === 0 ? (
                                    <th
                                        className="tv-sticky-left text-center"
                                        style={{
                                            ...getStickyStyle(0),
                                            top: 0,
                                            zIndex: 30,
                                        }}
                                    >
                                        <IconApp
                                            iconClassName={
                                                checkAll
                                                    ? "fas fa-square-check text-success m-0 padding-top-4"
                                                    : "fa-solid fa-square text-white m-0 padding-top-4"
                                            }
                                            fontSize="18px"
                                            onClick={() =>
                                                handleCheckAll(!checkAll)
                                            }
                                        />
                                    </th>
                                ) : (
                                    <th
                                        className={`text-size-12 ${
                                            isStickyColumn(index)
                                                ? "tv-sticky-left text-center"
                                                : "text-center"
                                        }`}
                                        style={
                                            isStickyColumn(index)
                                                ? {
                                                      ...getStickyStyle(index),
                                                      top: 0,
                                                      zIndex: 30,
                                                  }
                                                : {}
                                        }
                                    >
                                        {header}
                                    </th>
                                )}
                            </React.Fragment>
                        ))}
                        renderRow={(data, index) => {
                            const disabled = !!data?.has_open_cashing_campaign;
                            const studentKey = getStudentKey(data, index);
                            const isChecked = !!checkedStudents[studentKey];

                            return (
                                <>
                                    <td
                                        className="align-middle text-center text-nowrap tv-sticky-left"
                                        style={getStickyStyle(0)}
                                    >
                                        <IconApp
                                            iconClassName={
                                                disabled
                                                    ? "far fa-square-minus text-warning fa-2xl"
                                                    : isChecked
                                                      ? "fas fa-square-check text-success fa-2xl"
                                                      : "far fa-square text-grey fa-2xl"
                                            }
                                            isClickable={!disabled}
                                            onClick={
                                                disabled
                                                    ? () => {}
                                                    : () => {
                                                          handleCheck(
                                                              !isChecked,
                                                              studentKey,
                                                          );
                                                      }
                                            }
                                            description={
                                                disabled
                                                    ? "Ya pertenece a una campaña abierta"
                                                    : "_"
                                            }
                                            fontSize="18px"
                                        />
                                    </td>

                                    <td
                                        className="align-middle text-center text-nowrap tv-sticky-left"
                                        style={getStickyStyle(1)}
                                    >
                                        {index + 1}
                                    </td>

                                    <td
                                        className="text-center align-middle tv-sticky-left"
                                        style={getStickyStyle(2)}
                                    >
                                        {data?.student_number ? (
                                            <LinkToStudenFormApp
                                                student_number={
                                                    data.student_number
                                                }
                                            />
                                        ) : (
                                            "-"
                                        )}
                                    </td>

                                    <td
                                        className="align-middle tv-sticky-left"
                                        style={{
                                            ...getStickyStyle(3),
                                            whiteSpace: "normal",
                                            wordBreak: "break-word",
                                            overflowWrap: "anywhere",
                                            lineHeight: "1.2",
                                        }}
                                    >
                                        {data?.student_full_name || "--"}
                                    </td>

                                    <td
                                        className="align-middle tv-sticky-left"
                                        style={{
                                            ...getStickyStyle(4),
                                            whiteSpace: "normal",
                                            wordBreak: "break-word",
                                            overflowWrap: "anywhere",
                                            lineHeight: "1.2",
                                        }}
                                    >
                                        {data?.student_status ? (
                                            <div>
                                                <StudentStatusIcon
                                                    status={data.student_status}
                                                />
                                                <span className="ms-2">
                                                    {data.student_status}
                                                </span>
                                            </div>
                                        ) : (
                                            "--"
                                        )}
                                    </td>

                                    <td
                                        className="align-middle tv-sticky-left"
                                        style={{
                                            ...getStickyStyle(5),
                                            whiteSpace: "normal",
                                            wordBreak: "break-word",
                                            overflowWrap: "anywhere",
                                            lineHeight: "1.2",
                                        }}
                                    >
                                        {data?.curriculum_name || "--"}
                                    </td>

                                    <td
                                        className="align-middle text-right text-nowrap text-danger fw-bold tv-sticky-left"
                                        style={getStickyStyle(6)}
                                    >
                                        {formatMoney(data?.total_debt)}
                                    </td>

                                    {visibleMonthColumns.map((column) => (
                                        <td
                                            key={`${studentKey}-${column?.key}`}
                                            className="align-middle text-center text-nowrap text-black fw-bold"
                                        >
                                            {data?.months_map?.[column?.key] ? (
                                                <span>
                                                    {formatMoney(
                                                        data?.months_map?.[
                                                            column?.key
                                                        ],
                                                    )}
                                                </span>
                                            ) : (
                                                <span>-</span>
                                            )}
                                        </td>
                                    ))}
                                </>
                            );
                        }}
                    />
                </div>
            ) : (
                <Empty
                    image={Empty.PRESENTED_IMAGE_SIMPLE}
                    description="No se encontraron resultados."
                />
            )}
        </div>
    );
}
