import { CoordinationSelectApp } from "@components/CoordinationSelectApp";
import { SelectSearchMainCyclesApp } from "@components/SelectSearchMainCyclesApp";
import { TooltipAntdApp } from "@components/TooltipAntdApp";
import { orderMainCycles } from "@helpers/orderMainCycles";
import { startShow as startListBuildings } from "@redux/slices/operators/Building";
import { startShow as startListClassrooms } from "@redux/slices/operators/Classroom";
import { startShow as startListTeachers } from "@redux/slices/teachers/teacherSlice";
import { Empty } from "antd";
import React, { useEffect, useMemo, useState } from "react";
import { Button, Col, Form, Row, Table } from "react-bootstrap";
import { useDispatch, useSelector } from "react-redux";
import {
    CardContainer,
    CheckBoxApp,
    GroupInfoBadge,
    IconApp,
    LabelApp,
    SelectSearchApp,
} from "../../../components";
import { TableVirtual } from "../../../components/Crud/TableVirtual";
import { DatePickerRange } from "../../../components/DatePickerRange";
import { useForm } from "../../../hooks/useForm";
import {
    coordinationSetAttendanceReport,
    startGenerateReport,
    startShowAttendanceReport,
    startShow as startShowCoordinations,
} from "../../../redux/slices/teachers/v2/coordinationSlice";
import { startShow as listCycles } from "@redux/slices/teachers/v2/cycleSlice";

const defaultValues = {
    cycle: null,
    coordination_id: null,
    building_id: null,
    curriculum_ids: [],
    table_by: "COORDINATION",
    teachers: [],
    date: {
        from: "",
        to: "",
    },
    hide_empty_classroom_rows: true,
};

const getYesterdayDateString = () => {
    const date = new Date();
    date.setDate(date.getDate() - 1);

    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, "0");
    const day = String(date.getDate()).padStart(2, "0");

    return `${year}-${month}-${day}`;
};

// cycle: 93, 53;
// coordination_id: 13;
// from: 2025 - 01 - 06;
// to: 2025 - 03 - 22;
// get_by: TEACHER;

const getColorByPercentage = (percentage = 0, isInverse = false) => {
    const colors = isInverse
        ? ["#218838", "#3498db", "#f39c12", "#e67e22", "#e74c3c"]
        : ["#e74c3c", "#e67e22", "#f39c12", "#3498db", "#218838"];

    if (percentage >= 80) return colors[4];
    if (percentage >= 60) return colors[3];
    if (percentage >= 40) return colors[2];
    if (percentage >= 20) return colors[1];
    return colors[0];
};

const CLASSROOM_SLOT_COLUMNS = [
    // { key: "group", label: "Grupo" },
    { key: "teacher", label: "Docente", minWidth: "110px" },
    { key: "slot_attendance", label: "Asistencia", minWidth: "90px" },
    {
        key: "attendance_topic",
        label: "Avance\nprogramático",
        minWidth: "110px",
        wrapHeader: true,
    },
    { key: "round_time", label: "Rondín", minWidth: "75px" },
    {
        key: "round_teacher",
        label: "¿Docente\nasistió?",
        minWidth: "80px",
        wrapHeader: true,
    },
    {
        key: "round_discipline",
        label: "¿Disciplina\nen el aula?",
        minWidth: "92px",
        wrapHeader: true,
    },
];

const formatHour12 = (hour = 0) => {
    const normalizedHour = ((hour % 24) + 24) % 24;
    const meridiem = normalizedHour >= 12 ? "pm" : "am";
    const hour12 = normalizedHour % 12 || 12;

    return `${hour12}:00 ${meridiem}`;
};

const CLASSROOM_FIXED_SLOTS = Array.from({ length: 15 }, (_, index) => {
    const startHour = 7 + index;
    const endHour = startHour + 1;
    const start = `${String(startHour).padStart(2, "0")}:00`;
    const end = `${String(endHour).padStart(2, "0")}:00`;

    return {
        key: `${start} a ${end}`,
        label: `${formatHour12(startHour)} a ${formatHour12(endHour)}`,
        startMinutes: startHour * 60,
        endMinutes: endHour * 60,
    };
});

const toMinutes = (timeText = "") => {
    const [hourString = "", minuteString = ""] = timeText.split(":");
    const hour = Number(hourString);
    const minute = Number(minuteString);

    if (Number.isNaN(hour) || Number.isNaN(minute)) {
        return null;
    }

    return hour * 60 + minute;
};

const parseScheduleRange = (scheduleText = "") => {
    const [startText = "", endText = ""] = scheduleText.split(" a ");
    const startMinutes = toMinutes(startText.trim());
    const endMinutes = toMinutes(endText.trim());

    if (
        startMinutes === null ||
        endMinutes === null ||
        startMinutes >= endMinutes
    ) {
        return null;
    }

    return { startMinutes, endMinutes };
};

const hasOverlap = (scheduleRange, slot) =>
    scheduleRange.startMinutes < slot.endMinutes &&
    scheduleRange.endMinutes > slot.startMinutes;

const getGroupLabel = (group) => group?.name || group?.code || group || "-";

const addUniqueValue = (array, value) => {
    const cleanedValue =
        value === undefined || value === null ? "-" : `${value}`;

    if (!array.includes(cleanedValue)) {
        array.push(cleanedValue);
    }
};

const normalizeText = (value = "") => `${value}`.trim().toLowerCase();

const formatLocalDate = (date) =>
    `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(
        2,
        "0",
    )}-${String(date.getDate()).padStart(2, "0")}`;

const HoursTooltip = ({ data }) => {
    const hours = Object.keys(data || {});

    return (
        <TooltipAntdApp
            headerContent="Avance programático"
            bodyContent={
                <div>
                    {hours.length > 0 ? (
                        <Table striped bordered hover size="sm">
                            <thead>
                                <tr>
                                    {["Hora", "Tema"].map((h) => (
                                        <th
                                            className="bg-secondary text-center align-middle px-2"
                                            key={h}
                                        >
                                            {h}
                                        </th>
                                    ))}
                                </tr>
                            </thead>
                            <tbody>
                                {hours.map((h) => {
                                    const timeParts = h.split(":");
                                    timeParts.pop();
                                    const time = timeParts.join(":");

                                    return (
                                        <tr key={h}>
                                            <td className="text-center align-middle px-2">
                                                {time}
                                            </td>
                                            <td className="align-middle px-2">
                                                {data?.[h]?.planningSheet}
                                            </td>
                                        </tr>
                                    );
                                })}
                            </tbody>
                        </Table>
                    ) : (
                        <Empty description="Sin temas impartidos." />
                    )}
                </div>
            }
            placement="right"
        >
            <div
                className={`fa-solid fa-circle-info ms-2 text-size-16 ${
                    hours.length > 0 ? "text-info" : "text-danger"
                }`}
            />
        </TooltipAntdApp>
    );
};

const JustifyTooltip = ({ justify }) => {
    const hours = justify?.hours ?? 0;
    const description =
        hours > 0 ? `Horas justificadas: ${hours}` : "Sin justificaciones.";

    return (
        <TooltipAntdApp
            headerContent="Justificaciones"
            bodyContent={<div>{description}</div>}
            placement="right"
        >
            <div
                className={`fa-solid fa-circle-info ms-2 text-size-16 ${
                    hours > 0 ? "text-info" : "text-muted"
                }`}
            />
        </TooltipAntdApp>
    );
};

const AttendanceRoundsBySubjectsTooltip = ({ dataAttendanceRound }) => {
    const formatTag = (tag = "") =>
        tag
            .split("_")
            .map((w) => (w ? w[0].toUpperCase() + w.slice(1) : ""))
            .join(" ");

    return (
        <TooltipAntdApp
            headerContent="Detalles del rondín"
            maxWidth="30%"
            bodyContent={
                <div>
                    <Row>
                        <Col md={12}>
                            <LabelApp
                                title={"Hora del rondín"}
                                value={`${
                                    dataAttendanceRound?.attendance_time
                                        ? dataAttendanceRound.attendance_time +
                                          " hrs"
                                        : ""
                                }`}
                                linebreak
                            />
                        </Col>

                        <Col md={12}>
                            <LabelApp
                                title={"Observaciones"}
                                value={dataAttendanceRound?.observations}
                                linebreak
                            />
                        </Col>

                        <Col md={6}>
                            <LabelApp
                                title={"¿Docente asistió?"}
                                value={
                                    dataAttendanceRound?.teacher_attended ? (
                                        <>
                                            <span>Sí</span>
                                            <IconApp
                                                iconClassName="fa fa-circle-check text-green ms-2"
                                                fontSize="15px"
                                            />
                                        </>
                                    ) : (
                                        <>
                                            <span>No</span>
                                            <IconApp
                                                iconClassName="fa fa-circle-xmark text-red ms-2"
                                                fontSize="15px"
                                            />
                                        </>
                                    )
                                }
                                linebreak
                            />
                        </Col>

                        <Col md={6}>
                            <LabelApp
                                title={"¿Hubo disciplina en el aula?"}
                                value={
                                    dataAttendanceRound?.has_discipline ? (
                                        <>
                                            <span>Sí</span>
                                            <IconApp
                                                iconClassName="fa fa-circle-check text-green ms-2"
                                                fontSize="15px"
                                            />
                                        </>
                                    ) : (
                                        <>
                                            <span>No</span>
                                            <IconApp
                                                iconClassName="fa fa-circle-xmark text-red ms-2"
                                                fontSize="15px"
                                            />
                                        </>
                                    )
                                }
                                linebreak
                            />
                        </Col>

                        <Col md={12}>
                            <LabelApp
                                title={"Categorías seleccionadas"}
                                value={
                                    Array.isArray(
                                        dataAttendanceRound?.observation_tags,
                                    ) &&
                                    dataAttendanceRound.observation_tags
                                        .length > 0 ? (
                                        <>
                                            {dataAttendanceRound.observation_tags.map(
                                                (tag, index) => (
                                                    <span
                                                        key={index}
                                                        className={
                                                            "badge rounded-pill bg-primary-subtle text-primary border me-2 mb-1 observation-pill"
                                                        }
                                                    >
                                                        {formatTag(tag)}
                                                    </span>
                                                ),
                                            )}
                                        </>
                                    ) : (
                                        <>
                                            <span>No</span>
                                            <IconApp
                                                iconClassName="fa fa-circle-xmark text-red ms-2"
                                                fontSize="15px"
                                            />
                                        </>
                                    )
                                }
                                linebreak
                            />
                        </Col>
                    </Row>
                </div>
            }
            placement="right"
        >
            <div
                className={`fa-solid fa-circle-info ms-2 text-size-16 text-info`}
            />
        </TooltipAntdApp>
    );
};

export default function TeacherAttendancesReportScreen() {
    const dispatch = useDispatch();
    const [classroomSlotIndex, setClassroomSlotIndex] = useState(0);

    const { list: cyclesList } = useSelector((state) => state.cycle);
    const { attendanceReport } = useSelector((state) => state.coordination);
    const { list: teachersList } = useSelector((state) => state.teacher);
    const { list: buildingsList } = useSelector((state) => state.building);
    const { list: classroomsList } = useSelector((state) => state.classroom);

    const { values, handleInputChange, errors, setInputValue, reset } =
        useForm(defaultValues);
    const {
        cycle,
        coordination_id,
        building_id,
        date,
        table_by,
        teachers,
        hide_empty_classroom_rows,
    } = values;

    useEffect(() => {
        if (!date.from && !date.to) {
            const yesterday = getYesterdayDateString();

            setInputValue("date", {
                from: yesterday,
                to: yesterday,
            });
        }
    }, [date.from, date.to, setInputValue]);

    const searchKeys = useMemo(() => {
        if (table_by !== "SUBJECT") {
            if (table_by === "TEACHER") {
                return ["teacher_name", "coordination"];
            }

            return [];
        }

        return [
            "teacher",
            "class",
            "group_label",
            "classroom",
            "building",
            "classroom_building",
            "coordination",
        ];
    }, [table_by]);

    const searchableAttendanceReport = useMemo(() => {
        if (table_by === "SUBJECT") {
            return attendanceReport.map((item) => {
                const groupLabel =
                    item?.group?.name || item?.group?.code || item?.group || "";
                const classroom = item?.classroom || "";
                const building = item?.building || "";

                return {
                    ...item,
                    group_label: groupLabel,
                    classroom_building: `${classroom} ${building}`.trim(),
                };
            });
        }

        if (table_by === "TEACHER") {
            return attendanceReport.map((item) => ({
                ...item,
                teacher_name: item?.value?.teacher_name || "",
                coordination: item?.value?.coordination || "",
            }));
        }

        return attendanceReport;
    }, [attendanceReport, table_by]);

    const classroomsCatalog = useMemo(() => {
        const buildingById = new Map(
            (buildingsList || []).map((building) => [
                building.id,
                building.code,
            ]),
        );

        let classrooms = (classroomsList || []).map((classroom) => {
            const buildingCode =
                classroom?.building?.code ||
                buildingById.get(classroom?.building_id) ||
                "Sin edificio";

            return {
                ...classroom,
                building_code: buildingCode,
            };
        });

        if (building_id) {
            classrooms = classrooms.filter(
                (classroom) => `${classroom?.building_id}` === `${building_id}`,
            );
        }

        return classrooms.sort((left, right) => {
            const byBuilding = `${left.building_code}`.localeCompare(
                `${right.building_code}`,
                "es",
                {
                    numeric: true,
                },
            );

            if (byBuilding !== 0) {
                return byBuilding;
            }

            return `${left?.name || ""}`.localeCompare(
                `${right?.name || ""}`,
                "es",
                {
                    numeric: true,
                },
            );
        });
    }, [buildingsList, classroomsList, building_id]);

    const classroomMatrix = useMemo(() => {
        if (table_by !== "CLASSROOM") {
            return [];
        }

        if (!date?.from || !date?.to || classroomsCatalog.length === 0) {
            return [];
        }

        const fromDate = new Date(`${date.from}T00:00:00`);
        const toDate = new Date(`${date.to}T00:00:00`);

        if (
            Number.isNaN(fromDate.getTime()) ||
            Number.isNaN(toDate.getTime()) ||
            fromDate > toDate
        ) {
            return [];
        }

        const eventsIndex = {};
        (attendanceReport || []).forEach((item) => {
            const itemDate = item?.date;
            if (!itemDate) {
                return;
            }

            const normalizedBuilding = normalizeText(item?.building || "");
            const normalizedClassroom = normalizeText(item?.classroom || "");
            const itemClassroomKey = item?.classroom_id
                ? `id:${item.classroom_id}`
                : `name:${normalizedBuilding}::${normalizedClassroom}`;
            const indexKey = `${itemDate}__${itemClassroomKey}`;

            if (!eventsIndex[indexKey]) {
                eventsIndex[indexKey] = [];
            }

            eventsIndex[indexKey].push(item);
        });

        const rows = [];
        for (
            let current = new Date(fromDate);
            current <= toDate;
            current.setDate(current.getDate() + 1)
        ) {
            const dateText = formatLocalDate(current);

            classroomsCatalog.forEach((classroom) => {
                const normalizedBuilding = normalizeText(
                    classroom?.building_code || "",
                );
                const normalizedClassroom = normalizeText(
                    classroom?.name || "",
                );
                const classroomKey = classroom?.id
                    ? `id:${classroom.id}`
                    : `name:${normalizedBuilding}::${normalizedClassroom}`;
                const indexKey = `${dateText}__${classroomKey}`;
                const events = eventsIndex[indexKey] || [];

                const slotsData = {};
                CLASSROOM_FIXED_SLOTS.forEach((slot) => {
                    slotsData[slot.key] = {
                        group: [],
                        teacher: [],
                        slot_attendance: [],
                        attendance_topic: [],
                        round_time: [],
                        round_teacher: [],
                        round_discipline: [],
                    };
                });

                events.forEach((event) => {
                    const scheduleRange = parseScheduleRange(
                        event?.schedule_text || "",
                    );
                    if (!scheduleRange) {
                        return;
                    }

                    CLASSROOM_FIXED_SLOTS.forEach((slot) => {
                        if (!hasOverlap(scheduleRange, slot)) {
                            return;
                        }

                        const slotValues = slotsData[slot.key];
                        addUniqueValue(
                            slotValues.group,
                            getGroupLabel(event?.group),
                        );
                        addUniqueValue(
                            slotValues.teacher,
                            event?.teacher || "-",
                        );
                        addUniqueValue(
                            slotValues.slot_attendance,
                            event?.slot_attendance?.[slot.key] || "-",
                        );
                        addUniqueValue(
                            slotValues.attendance_topic,
                            event?.attendance_topic_hours ? "Sí" : "No",
                        );
                        addUniqueValue(
                            slotValues.round_time,
                            event?.attendance_round?.attendance_time
                                ? `${event.attendance_round.attendance_time} hrs`
                                : "-",
                        );
                        addUniqueValue(
                            slotValues.round_teacher,
                            event?.attendance_round
                                ? event.attendance_round.teacher_attended
                                    ? "Sí"
                                    : "No"
                                : "-",
                        );
                        addUniqueValue(
                            slotValues.round_discipline,
                            event?.attendance_round
                                ? event.attendance_round.has_discipline
                                    ? "Sí"
                                    : "No"
                                : "-",
                        );
                    });
                });

                const mergedSlots = {};
                CLASSROOM_FIXED_SLOTS.forEach((slot) => {
                    const slotValues = slotsData[slot.key];
                    mergedSlots[slot.key] = {
                        group: slotValues.group.length
                            ? slotValues.group.join("\n")
                            : "-",
                        teacher: slotValues.teacher.length
                            ? slotValues.teacher.join("\n")
                            : "-",
                        slot_attendance: slotValues.slot_attendance.length
                            ? slotValues.slot_attendance.join("\n")
                            : "-",
                        attendance_topic: slotValues.attendance_topic.length
                            ? slotValues.attendance_topic.join("\n")
                            : "-",
                        round_time: slotValues.round_time.length
                            ? slotValues.round_time.join("\n")
                            : "-",
                        round_teacher: slotValues.round_teacher.length
                            ? slotValues.round_teacher.join("\n")
                            : "-",
                        round_discipline: slotValues.round_discipline.length
                            ? slotValues.round_discipline.join("\n")
                            : "-",
                    };
                });

                rows.push({
                    date: dateText,
                    building: classroom?.building_code || "Sin edificio",
                    classroom: classroom?.name || "Sin aula",
                    classroom_id: classroom?.id || null,
                    slots: mergedSlots,
                });
            });
        }

        return rows;
    }, [table_by, date?.from, date?.to, classroomsCatalog, attendanceReport]);

    const classroomVisibleSlots = useMemo(() => {
        if (table_by !== "CLASSROOM") {
            return [];
        }

        return CLASSROOM_FIXED_SLOTS.filter((slot) =>
            classroomMatrix.some((row) =>
                CLASSROOM_SLOT_COLUMNS.some(
                    (column) => row?.slots?.[slot.key]?.[column.key] !== "-",
                ),
            ),
        );
    }, [table_by, classroomMatrix]);

    useEffect(() => {
        dispatch(
            listCycles({
                asList: true,
                emptyOption: true,
                only_started_cycles: true,
            }),
        );
        dispatch(startShowCoordinations({ asList: 1 }));
        dispatch(startListTeachers({ asList: true }));
        dispatch(startListBuildings({ asList: 1 }, false));
        dispatch(startListClassrooms({ asList: 1 }));
    }, []);

    // useEffect(() => {
    //     dispatch(coordinationSetAttendanceReport([]));
    // }, [values]);

    useEffect(() => {
        dispatch(coordinationSetAttendanceReport([]));
    }, [table_by]);

    const startSearch = () => {
        if (cycle && date.from && date.to) {
            dispatch(startShowAttendanceReport(values));
        }
    };

    const clearData = () => {
        reset();
        setInputValue("date", {
            from: "",
            to: "",
        });
        dispatch(coordinationSetAttendanceReport([]));
    };

    const getTableHeaders = () => {
        switch (table_by) {
            case "COORDINATION":
                return [
                    "Coordinación",
                    "Total de clases",
                    "Clases rondineadas",
                    "Porcentaje de rondín",
                    "Total de horas",
                    "Total de faltas",
                    "Porcentaje de asistencias",
                    "Porcentaje de faltas",
                ];

            case "TEACHER":
                return [
                    "N° de docente",
                    "Docente",
                    "Total de clases",
                    "Total de avances programáticos cargados",
                    "Porcentaje de avances programáticos cargados",
                    "Total de horas",
                    "Total de faltas",
                    // "Porcentaje de asistencias",
                    "Porcentaje de faltas",
                    "Coordinación",
                ];

            case "SUBJECT":
                return [
                    "Fecha",
                    "Horario",
                    "Materia",
                    "Docente",
                    "Grupo",
                    "Aula / Edificio",
                    "Total de horas",
                    // "Total de faltas",
                    "Avance programático",
                    "Rondín",
                    "Coordinación",
                ];

            default:
                return [];
        }
    };

    const onRadioChange = (e) => {
        setInputValue("table_by", e.target.id);
    };

    const handleExport = () => {
        dispatch(startGenerateReport(values));
    };

    const canShowExport =
        table_by === "CLASSROOM"
            ? classroomVisibleSlots.length > 0
            : attendanceReport.length > 0;

    const classroomSlotsCount = classroomVisibleSlots.length;
    const safeClassroomSlotIndex =
        classroomSlotsCount > 0
            ? Math.min(classroomSlotIndex, classroomSlotsCount - 1)
            : 0;
    const currentClassroomSlot = classroomVisibleSlots[safeClassroomSlotIndex];
    const classroomSlotsToRender = currentClassroomSlot
        ? [currentClassroomSlot]
        : [];
    const classroomRowsToRender = useMemo(() => {
        if (table_by !== "CLASSROOM") {
            return [];
        }

        if (!hide_empty_classroom_rows || !currentClassroomSlot) {
            return classroomMatrix;
        }

        return classroomMatrix.filter((row) =>
            CLASSROOM_SLOT_COLUMNS.some(
                (column) =>
                    row?.slots?.[currentClassroomSlot.key]?.[column.key] !==
                    "-",
            ),
        );
    }, [
        table_by,
        hide_empty_classroom_rows,
        currentClassroomSlot,
        classroomMatrix,
    ]);

    const tableVirtuosoPalette = {
        bgBase: "#ffffff",
        bgAlt: "#fafafa",
        bgHover: "#f5f5f5",
        headerBg: "#0f4c8a",
        border: "#dee2e6",
        borderHeader: "rgba(255, 255, 255, 0.35)",
        borderBottom: "#8aa2bf8b",
        separator: "#8aa2bf",
        topSeparator: "#b8cbe2",
    };

    const getClassroomRowBackground = (rowIndex = 0) =>
        rowIndex % 2 === 0
            ? tableVirtuosoPalette.bgBase
            : tableVirtuosoPalette.bgAlt;

    const renderClassroomRoundValue = (value = "") => {
        const normalized = `${value}`.trim().toLowerCase();

        if (["sí", "si", "asistencia"].includes(normalized)) {
            return (
                <IconApp
                    iconClassName="fas fa-check text-green"
                    fontSize="15px"
                />
            );
        }

        if (["no", "falta"].includes(normalized)) {
            return (
                <IconApp
                    iconClassName="fas fa-xmark text-red"
                    fontSize="15px"
                />
            );
        }

        return <span className="text-muted">-</span>;
    };

    const renderClassroomCellContent = (columnKey, rawValue) => {
        const valueText = `${rawValue ?? "-"}`;

        if (
            ![
                "slot_attendance",
                "attendance_topic",
                "round_teacher",
                "round_discipline",
            ].includes(columnKey)
        ) {
            return valueText;
        }

        const values = valueText.split("\n").filter((value) => value !== "");

        return (
            <div className="d-flex flex-column align-items-center justify-content-center gap-1">
                {values.map((value, index) => (
                    <span
                        key={`${columnKey}-${index}`}
                        className="d-inline-flex align-items-center justify-content-center"
                    >
                        {renderClassroomRoundValue(value)}
                    </span>
                ))}
            </div>
        );
    };

    useEffect(() => {
        if (table_by !== "CLASSROOM") {
            if (classroomSlotIndex !== 0) {
                setClassroomSlotIndex(0);
            }
            return;
        }

        if (classroomSlotsCount === 0) {
            if (classroomSlotIndex !== 0) {
                setClassroomSlotIndex(0);
            }
            return;
        }

        if (classroomSlotIndex > classroomSlotsCount - 1) {
            setClassroomSlotIndex(classroomSlotsCount - 1);
        }
    }, [table_by, classroomSlotsCount, classroomSlotIndex]);

    useEffect(() => {
        if (table_by === "CLASSROOM") {
            setClassroomSlotIndex(0);
        }
    }, [attendanceReport, table_by]);

    return (
        <CardContainer title="Asistencias docentes">
            <Row>
                <Col md={3}>
                    <SelectSearchMainCyclesApp
                        title="Ciclo"
                        placeholder="Seleccione un ciclo"
                        name="cycle"
                        value={cycle}
                        required
                        onChange={handleInputChange}
                        options={orderMainCycles(cyclesList, false)}
                        errorText={errors.cycle && errors.cycle[0]}
                    />
                </Col>
                <Col md={3}>
                    <DatePickerRange
                        title="Rango de fechas (*)"
                        toMinDateFrom
                        from={date.from}
                        to={date.to}
                        path="date"
                        disableTo
                        handleInputChange={handleInputChange}
                    />
                </Col>
                <Col md={6}>
                    <CoordinationSelectApp
                        coordination_name="coordination_id"
                        coordination_id={coordination_id}
                        handleInputChange={handleInputChange}
                        errors={errors}
                    />
                </Col>
                <Col md={6}>
                    <SelectSearchApp
                        title="Docentes"
                        placeholder="Seleccione un docente"
                        name="teachers"
                        value={teachers}
                        multiple={true}
                        onChange={handleInputChange}
                        options={teachersList.map((d) => ({
                            value: d.no_employe,
                            label: d.username,
                        }))}
                        errorText={errors.teachers && errors.teachers[0]}
                    />
                </Col>
                <Col md={6}>
                    <SelectSearchApp
                        title="Edificio"
                        placeholder="Seleccione un edificio"
                        name="building_id"
                        value={building_id}
                        onChange={handleInputChange}
                        options={buildingsList.map((building) => ({
                            value: building.id,
                            label: building?.code,
                        }))}
                        errorText={errors.building_id && errors.building_id[0]}
                    />
                </Col>
            </Row>

            <Row className="mt-4">
                <Form>
                    <Form.Check
                        className="mb-2"
                        type="radio"
                        id="COORDINATION"
                        label={
                            <span className="h5">
                                Asistencias por coordinación
                            </span>
                        }
                        onChange={onRadioChange}
                        name="table_by"
                        defaultChecked
                    />
                    <Form.Check
                        className="mb-2"
                        type="radio"
                        id="TEACHER"
                        label={
                            <span className="h5">Asistencias por docentes</span>
                        }
                        onChange={onRadioChange}
                        name="table_by"
                    />
                    <Form.Check
                        className="mb-2"
                        type="radio"
                        id="SUBJECT"
                        label={
                            <span className="h5">Asistencias por materias</span>
                        }
                        onChange={onRadioChange}
                        name="table_by"
                    />
                    <Form.Check
                        type="radio"
                        id="CLASSROOM"
                        label={
                            <span className="h5">Asistencias por aulas</span>
                        }
                        onChange={onRadioChange}
                        name="table_by"
                    />
                </Form>

                {canShowExport && (
                    <div className="my-3">
                        <Button
                            className="btn-app-green-with-hover"
                            onClick={() => handleExport()}
                        >
                            <IconApp iconClassName="fas fa-file-excel" />{" "}
                            Exportar reporte
                        </Button>
                    </div>
                )}

                <Row className="text-center mt-1 mb-3">
                    <Col md={12}>
                        <Button
                            onClick={startSearch}
                            disabled={(cycle && !date.from) || !date.to}
                        >
                            Realizar búsqueda
                            <IconApp iconClassName="fas fa-search ml-2" />
                        </Button>

                        <Button
                            variant="secondary"
                            className="ms-3"
                            disabled={cycle && !date.from && !date.to}
                            onClick={clearData}
                        >
                            Limpiar
                        </Button>
                    </Col>
                </Row>

                <hr />
            </Row>
            <Row>
                {cycle && date.from && date.to && (
                    <>
                        {table_by === "CLASSROOM" ? (
                            classroomSlotsCount > 0 ? (
                                <>
                                    <div className="d-flex flex-column align-items-center justify-content-center mb-2">
                                        <div className="text-center mb-2">
                                            <strong className="text-size-13">
                                                Bloque horario:{" "}
                                                {currentClassroomSlot?.label ||
                                                    "Sin horarios"}
                                            </strong>
                                        </div>

                                        <div className="d-flex align-items-center justify-content-center flex-wrap gap-2 mt-2">
                                            <Button
                                                size="sm"
                                                variant="outline-primary"
                                                title="Ir al primer bloque"
                                                className="py-1"
                                                onClick={() =>
                                                    setClassroomSlotIndex(0)
                                                }
                                                disabled={
                                                    safeClassroomSlotIndex === 0
                                                }
                                            >
                                                <IconApp
                                                    iconClassName="fas fa-angles-left"
                                                    description="Ir al primer bloque"
                                                />
                                            </Button>

                                            <Button
                                                size="sm"
                                                variant="outline-primary"
                                                className="py-1"
                                                onClick={() =>
                                                    setClassroomSlotIndex(
                                                        (prev) =>
                                                            Math.max(
                                                                prev - 1,
                                                                0,
                                                            ),
                                                    )
                                                }
                                                disabled={
                                                    safeClassroomSlotIndex === 0
                                                }
                                            >
                                                <IconApp iconClassName="fas fa-chevron-left me-1" />
                                                Anterior
                                            </Button>

                                            <span className="small text-muted fw-bold mx-2">
                                                {classroomSlotsCount > 0
                                                    ? `${safeClassroomSlotIndex + 1} / ${classroomSlotsCount}`
                                                    : "0 / 0"}
                                            </span>

                                            <Button
                                                size="sm"
                                                variant="outline-primary"
                                                className="py-1"
                                                onClick={() =>
                                                    setClassroomSlotIndex(
                                                        (prev) =>
                                                            Math.min(
                                                                prev + 1,
                                                                classroomSlotsCount -
                                                                    1,
                                                            ),
                                                    )
                                                }
                                                disabled={
                                                    classroomSlotsCount === 0 ||
                                                    safeClassroomSlotIndex >=
                                                        classroomSlotsCount - 1
                                                }
                                            >
                                                Siguiente
                                                <IconApp iconClassName="fas fa-chevron-right ms-1" />
                                            </Button>

                                            <Button
                                                size="sm"
                                                variant="outline-primary"
                                                title="Ir al último bloque"
                                                className="py-1"
                                                onClick={() =>
                                                    setClassroomSlotIndex(
                                                        Math.max(
                                                            classroomSlotsCount -
                                                                1,
                                                            0,
                                                        ),
                                                    )
                                                }
                                                disabled={
                                                    classroomSlotsCount === 0 ||
                                                    safeClassroomSlotIndex >=
                                                        classroomSlotsCount - 1
                                                }
                                            >
                                                <IconApp
                                                    iconClassName="fas fa-angles-right"
                                                    description="Ir al último bloque"
                                                />
                                            </Button>
                                        </div>
                                    </div>

                                    <Row className="d-flex justify-content-between w-100">
                                        <Col md={"auto"}>
                                            <CheckBoxApp
                                                label="Ocultar registros vacíos en bloque actual"
                                                name="hide_empty_classroom_rows"
                                                className={
                                                    "custom-checkbox-app"
                                                }
                                                style={{
                                                    fontSize: "13px",
                                                }}
                                                onChange={handleInputChange}
                                                checked={
                                                    hide_empty_classroom_rows
                                                }
                                                errorText={
                                                    errors.hide_empty_classroom_rows &&
                                                    errors
                                                        .hide_empty_classroom_rows[0]
                                                }
                                            />
                                        </Col>

                                        <Col md={"auto"} className="mt-1">
                                            <IconApp
                                                iconClassName={
                                                    "fa fa-lightbulb-on text-info me-1"
                                                }
                                            />
                                            <span className="text-size-11">
                                                Deslice dentro de la tabla para
                                                ver más registros.
                                            </span>
                                        </Col>
                                    </Row>

                                    <div
                                        className="table-responsive-horizontal"
                                        style={{
                                            maxHeight: "70vh",
                                            overflowY: "auto",
                                        }}
                                    >
                                        <Table
                                            bordered
                                            hover
                                            size="sm"
                                            style={{
                                                width: "max-content",
                                                minWidth: "100%",
                                                marginBottom: 0,
                                            }}
                                        >
                                            <thead
                                                style={{
                                                    position: "sticky",
                                                    top: 0,
                                                    zIndex: 5,
                                                    backgroundColor:
                                                        tableVirtuosoPalette.headerBg,
                                                }}
                                            >
                                                <tr className="bg-blue text-size-12">
                                                    <th
                                                        rowSpan={2}
                                                        className="align-middle text-center"
                                                        style={{
                                                            backgroundColor:
                                                                tableVirtuosoPalette.headerBg,
                                                            whiteSpace:
                                                                "nowrap",
                                                        }}
                                                    >
                                                        Fecha
                                                    </th>

                                                    <th
                                                        rowSpan={2}
                                                        className="align-middle text-center"
                                                        style={{
                                                            backgroundColor:
                                                                tableVirtuosoPalette.headerBg,
                                                            whiteSpace:
                                                                "nowrap",
                                                        }}
                                                    >
                                                        Edificio
                                                    </th>

                                                    <th
                                                        rowSpan={2}
                                                        className="align-middle text-center"
                                                        style={{
                                                            backgroundColor:
                                                                tableVirtuosoPalette.headerBg,
                                                            borderRight: `2px solid #fff`,
                                                            whiteSpace:
                                                                "nowrap",
                                                        }}
                                                    >
                                                        Aula
                                                    </th>

                                                    {classroomSlotsToRender.map(
                                                        (slot, slotIndex) => (
                                                            <th
                                                                key={slot.key}
                                                                colSpan={
                                                                    CLASSROOM_SLOT_COLUMNS.length
                                                                }
                                                                className="align-middle text-center"
                                                                style={{
                                                                    backgroundColor:
                                                                        tableVirtuosoPalette.headerBg,
                                                                    borderColor:
                                                                        tableVirtuosoPalette.borderHeader,
                                                                    borderLeft:
                                                                        slotIndex >
                                                                        0
                                                                            ? `2px solid #fff`
                                                                            : undefined,
                                                                    whiteSpace:
                                                                        "nowrap",
                                                                }}
                                                            >
                                                                {slot.label}
                                                            </th>
                                                        ),
                                                    )}
                                                </tr>

                                                <tr className="bg-blue text-size-12">
                                                    {classroomSlotsToRender.flatMap(
                                                        (slot) =>
                                                            CLASSROOM_SLOT_COLUMNS.map(
                                                                (
                                                                    column,
                                                                    columnIndex,
                                                                ) => (
                                                                    <th
                                                                        key={`${slot.key}-${column.key}`}
                                                                        className="align-middle text-center"
                                                                        style={{
                                                                            backgroundColor:
                                                                                tableVirtuosoPalette.headerBg,
                                                                            minWidth:
                                                                                column.minWidth ||
                                                                                "110px",
                                                                            borderColor:
                                                                                tableVirtuosoPalette.borderHeader,
                                                                            borderLeft:
                                                                                columnIndex ===
                                                                                0
                                                                                    ? `2px solid #fff`
                                                                                    : undefined,
                                                                            whiteSpace:
                                                                                column.wrapHeader
                                                                                    ? "pre-line"
                                                                                    : "nowrap",
                                                                            lineHeight:
                                                                                column.wrapHeader
                                                                                    ? "1.1"
                                                                                    : undefined,
                                                                        }}
                                                                    >
                                                                        {
                                                                            column.label
                                                                        }
                                                                    </th>
                                                                ),
                                                            ),
                                                    )}
                                                </tr>
                                            </thead>

                                            <tbody>
                                                {classroomRowsToRender.map(
                                                    (rowData, rowIndex) => (
                                                        <tr
                                                            key={`${rowData.date}-${rowData.classroom_id || rowData.classroom}-${rowIndex}`}
                                                        >
                                                            <td
                                                                className="align-middle text-center text-nowrap text-size-11 fw-bold"
                                                                style={{
                                                                    backgroundColor:
                                                                        getClassroomRowBackground(
                                                                            rowIndex,
                                                                        ),
                                                                    borderBottom: `1px solid ${tableVirtuosoPalette.borderBottom}`,
                                                                }}
                                                            >
                                                                {rowData.date}
                                                            </td>

                                                            <td
                                                                className="align-middle text-center text-nowrap fw-bold"
                                                                style={{
                                                                    backgroundColor:
                                                                        getClassroomRowBackground(
                                                                            rowIndex,
                                                                        ),
                                                                    borderBottom: `1px solid ${tableVirtuosoPalette.borderBottom}`,
                                                                }}
                                                            >
                                                                {
                                                                    rowData.building
                                                                }
                                                            </td>

                                                            <td
                                                                className="align-middle text-center text-nowrap fw-bold"
                                                                style={{
                                                                    backgroundColor:
                                                                        getClassroomRowBackground(
                                                                            rowIndex,
                                                                        ),
                                                                    borderBottom: `1px solid ${tableVirtuosoPalette.borderBottom}`,
                                                                }}
                                                            >
                                                                {
                                                                    rowData.classroom
                                                                }
                                                            </td>

                                                            {classroomSlotsToRender.flatMap(
                                                                (slot) =>
                                                                    CLASSROOM_SLOT_COLUMNS.map(
                                                                        (
                                                                            column,
                                                                            columnIndex,
                                                                        ) => (
                                                                            <td
                                                                                key={`${rowData.date}-${rowData.classroom_id || rowData.classroom}-${slot.key}-${column.key}`}
                                                                                className="align-middle text-center text-black"
                                                                                style={{
                                                                                    whiteSpace:
                                                                                        "pre-line",
                                                                                    borderColor:
                                                                                        tableVirtuosoPalette.border,
                                                                                    borderLeft:
                                                                                        columnIndex ===
                                                                                        0
                                                                                            ? `2px solid ${tableVirtuosoPalette.separator}`
                                                                                            : undefined,
                                                                                    borderBottom: `1px solid ${tableVirtuosoPalette.borderBottom}`,
                                                                                    backgroundColor:
                                                                                        getClassroomRowBackground(
                                                                                            rowIndex,
                                                                                        ),
                                                                                    padding:
                                                                                        "0.46rem 0.45rem",
                                                                                }}
                                                                            >
                                                                                {renderClassroomCellContent(
                                                                                    column.key,
                                                                                    rowData
                                                                                        ?.slots?.[
                                                                                        slot
                                                                                            .key
                                                                                    ]?.[
                                                                                        column
                                                                                            .key
                                                                                    ] ||
                                                                                        "-",
                                                                                )}
                                                                            </td>
                                                                        ),
                                                                    ),
                                                            )}
                                                        </tr>
                                                    ),
                                                )}
                                            </tbody>
                                        </Table>
                                    </div>
                                </>
                            ) : (
                                <Row>
                                    <Empty description="Sin aulas para mostrar." />
                                </Row>
                            )
                        ) : (
                            <>
                                {attendanceReport.length > 0 ? (
                                    <TableVirtual
                                        tableId="attendances-report"
                                        tableHeaders={getTableHeaders()}
                                        hasActions={false}
                                        data={searchableAttendanceReport}
                                        maxHeight={1200}
                                        striped
                                        hover
                                        searchKeys={searchKeys}
                                        classNameTrHeader="bg-blue"
                                        renderRow={(data) => (
                                            <>
                                                {table_by == "COORDINATION" && (
                                                    <>
                                                        <td className="align-middle">
                                                            {data?.key}
                                                        </td>
                                                        <td className="align-middle text-center text-nowrap ">
                                                            {
                                                                data?.value
                                                                    ?.count_class
                                                            }
                                                        </td>
                                                        <td className="align-middle text-center text-nowrap ">
                                                            {data?.value
                                                                ?.rounds_count ||
                                                                0}
                                                        </td>
                                                        <td
                                                            style={{
                                                                color: getColorByPercentage(
                                                                    data?.value
                                                                        ?.percentage_rounds,
                                                                    false,
                                                                ),
                                                            }}
                                                            className="align-middle text-center text-nowrap "
                                                        >
                                                            {data?.value
                                                                ?.percentage_rounds ||
                                                                0}
                                                            %
                                                        </td>
                                                        <td className="align-middle text-center text-nowrap ">
                                                            {
                                                                data?.value
                                                                    ?.total_hours
                                                            }
                                                        </td>
                                                        <td className="align-middle text-center text-nowrap ">
                                                            {
                                                                data?.value
                                                                    ?.hours_faults
                                                            }
                                                        </td>
                                                        <td
                                                            style={{
                                                                color: getColorByPercentage(
                                                                    data?.value
                                                                        ?.percentage_assists,
                                                                ),
                                                            }}
                                                            className="align-middle text-center text-nowrap "
                                                        >
                                                            {data?.value
                                                                ?.percentage_assists ||
                                                                0}
                                                            %
                                                        </td>
                                                        <td
                                                            style={{
                                                                color: getColorByPercentage(
                                                                    data?.value
                                                                        ?.percentage_faults,
                                                                    true,
                                                                ),
                                                            }}
                                                            className="align-middle text-center text-nowrap "
                                                        >
                                                            {data?.value
                                                                ?.percentage_faults ||
                                                                0}
                                                            %
                                                        </td>
                                                    </>
                                                )}
                                                {table_by == "TEACHER" && (
                                                    <>
                                                        <td className="align-middle text-center ">
                                                            #{" "}
                                                            {
                                                                data?.value
                                                                    ?.no_employe
                                                            }
                                                        </td>
                                                        <td className="align-middle ">
                                                            {
                                                                data?.value
                                                                    ?.teacher_name
                                                            }
                                                        </td>
                                                        <td className="align-middle text-center text-nowrap ">
                                                            {
                                                                data?.value
                                                                    ?.count_class
                                                            }
                                                        </td>
                                                        <td className="align-middle text-center text-nowrap ">
                                                            {data?.value
                                                                ?.attendance_topics ||
                                                                0}
                                                        </td>
                                                        <td
                                                            style={{
                                                                color: getColorByPercentage(
                                                                    data?.value
                                                                        ?.percentage_attendances,
                                                                ),
                                                            }}
                                                            className="align-middle text-center text-nowrap "
                                                        >
                                                            {data?.value
                                                                ?.percentage_attendances ||
                                                                "0"}
                                                            %
                                                        </td>
                                                        <td className="align-middle text-center text-nowrap ">
                                                            {
                                                                data?.value
                                                                    ?.total_hours
                                                            }
                                                        </td>
                                                        <td className="align-middle text-center text-nowrap ">
                                                            {
                                                                data?.value
                                                                    ?.hours_faults
                                                            }
                                                        </td>
                                                        <td
                                                            style={{
                                                                color: getColorByPercentage(
                                                                    data?.value
                                                                        ?.percentage_faults,
                                                                    true,
                                                                ),
                                                            }}
                                                            className="align-middle text-center text-nowrap "
                                                        >
                                                            {data?.value
                                                                ?.percentage_faults ||
                                                                0}
                                                            %
                                                        </td>
                                                        <td className="align-middle text-center text-nowrap ">
                                                            {data?.value
                                                                ?.coordination ||
                                                                "0"}
                                                        </td>
                                                    </>
                                                )}
                                                {table_by == "SUBJECT" && (
                                                    <>
                                                        <td className="align-middle text-center text-nowrap ">
                                                            {data?.date}
                                                        </td>
                                                        <td className="align-middle text-center text-nowrap ">
                                                            {
                                                                data?.schedule_text
                                                            }
                                                        </td>
                                                        <td className="align-middle text-center ">
                                                            {data?.class}
                                                        </td>
                                                        <td className="align-middle text-nowrap ">
                                                            {data?.teacher}
                                                        </td>
                                                        <td className="align-middle text-center ">
                                                            <GroupInfoBadge
                                                                group={
                                                                    data?.group
                                                                }
                                                                placeholder={
                                                                    data?.group
                                                                        ?.name ||
                                                                    data?.group
                                                                        ?.code ||
                                                                    data?.group ||
                                                                    "-"
                                                                }
                                                            />
                                                        </td>
                                                        <td className="align-middle text-center ">
                                                            <div>
                                                                {data?.classroom ||
                                                                    "-"}
                                                            </div>
                                                            <div className="text-muted">
                                                                {data?.building ||
                                                                    "-"}
                                                            </div>
                                                        </td>
                                                        <td className="align-middle text-center text-nowrap ">
                                                            {
                                                                data?.hours_worked_compare
                                                            }
                                                            <JustifyTooltip
                                                                justify={
                                                                    data?.justify
                                                                }
                                                            />
                                                        </td>
                                                        <td className="align-middle text-center text-nowrap ">
                                                            {data.attendance_topic_hours
                                                                ? "Sí"
                                                                : "No"}
                                                            <HoursTooltip
                                                                data={
                                                                    data.attendance_topic_hours
                                                                }
                                                            />
                                                        </td>
                                                        <td className="align-middle text-center text-nowrap ">
                                                            {data?.attendance_round ? (
                                                                <>
                                                                    <span>
                                                                        {data
                                                                            .attendance_round
                                                                            .attendance_time
                                                                            ? `${data.attendance_round.attendance_time} hrs`
                                                                            : "Sin hora"}
                                                                    </span>
                                                                    <AttendanceRoundsBySubjectsTooltip
                                                                        dataAttendanceRound={
                                                                            data?.attendance_round
                                                                        }
                                                                    />
                                                                </>
                                                            ) : (
                                                                "-"
                                                            )}
                                                        </td>
                                                        <td className="align-middle text-nowrap ">
                                                            {data?.coordination}
                                                        </td>
                                                    </>
                                                )}
                                            </>
                                        )}
                                    />
                                ) : (
                                    <Row>
                                        <Empty description="Sin asistencias para mostrar." />
                                    </Row>
                                )}
                            </>
                        )}
                    </>
                )}
            </Row>
        </CardContainer>
    );
}
