import React, { useEffect, useMemo, useState } from "react";
import { Button, Col, Row } from "react-bootstrap";
import { useDispatch, useSelector } from "react-redux";
import { CardContainer, IconApp } from "@components";
import { CrudApp } from "@components/Crud/CrudApp";
import { CoordinationSelectApp } from "@components/CoordinationSelectApp";
import { SelectSearchMainCyclesApp } from "@components/SelectSearchMainCyclesApp";
import { SelectTeachersApp } from "@components/schedule/SelectTeachersApp";
import { TooltipAntdApp } from "@components/TooltipAntdApp";
import { orderMainCycles } from "@helpers/orderMainCycles";
import { useForm } from "@hooks/useForm";
import { startShow as startListCycles } from "@redux/slices/teachers/v2/cycleSlice";
import { startShow as startListCoordination } from "@redux/slices/teachers/v2/coordinationSlice";
import { startShow as startListTeachers } from "@redux/slices/teachers/teacherSlice";
import {
    clearReport,
    startExportProgrammaticAdvancesReport,
    startShowProgrammaticAdvancesReport,
} from "@redux/slices/users/ProgrammaticAdvances";
import ModalApp from "@components/ModalApp";
import { ProgrammaticAdvanceTable } from "@components/ProgrammaticAdvance/ProgrammaticAdvanceTable";
import {
    startShowPlanningSheetCriteria,
    startShowPlanningSheetsList,
} from "@redux/slices/users/PlanningSheets";

const defaultValues = {
    page: 1,
    query: "",
    number_rows: 25,
    cycles: null,
    coordination_id: null,
    teacher_id: null,
    refresh: false,
    errors: {},
};

const modalDefaultValues = {
    page: 1,
    query: "",
    number_rows: 50,
    class_type: null,
    only_unseen: false,
    refresh: false,
    errors: {},
};

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

    const { report } = useSelector((state) => state.programmaticAdvances);
    const { list: cyclesList } = useSelector((state) => state.cycle);
    const { list: teachersList } = useSelector((state) => state.teacher);
    const { list: planningSheetsList } = useSelector(
        (state) => state.planningSheets,
    );

    const [showModal, setShowModal] = useState(false);
    const [activeRow, setActiveRow] = useState(null);
    const [criteriaList, setCriteriaList] = useState([]);

    const { values, handleInputChange, setInputValue } = useForm(defaultValues);
    const {
        values: modalValues,
        handleInputChange: handleModalInputChange,
        setInputValue: setModalInputValue,
        setFormValues: setModalFormValues,
    } = useForm(modalDefaultValues);
    const {
        cycles,
        coordination_id,
        teacher_id,
        page,
        number_rows,
        query,
        refresh,
        errors,
    } = values;

    const { enable_programmatic_advance_evaluation_criteria } = useSelector(
        (state) => state.config,
    );

    const showEvaluationCriteria =
        !!enable_programmatic_advance_evaluation_criteria &&
        !!activeRow?.teacher_id;

    const handleReportInputChange = (event) => {
        handleInputChange(event);

        if (event.target.name !== "page") {
            setInputValue("page", 1);
        }
    };

    const setReportInputValue = (name, value) => {
        setInputValue(name, value);

        if (name !== "page" && name !== "refresh") {
            setInputValue("page", 1);
        }
    };

    const filteredPlanningSheets = useMemo(() => {
        const search = modalValues.query?.trim().toLowerCase();
        const classType = modalValues.class_type;
        const onlyUnseen = modalValues.only_unseen;

        let filtered = planningSheetsList || [];

        if (search) {
            filtered = filtered.filter((planningSheet) =>
                [
                    planningSheet.topic,
                    planningSheet.content,
                    planningSheet.class_type,
                    planningSheet.objectives_section,
                    planningSheet.sequence,
                    planningSheet.resources,
                    planningSheet.evaluation_technique,
                    planningSheet.evaluation_instrument,
                    planningSheet.activities_tasks,
                ]
                    .filter(Boolean)
                    .some((value) =>
                        String(value).toLowerCase().includes(search),
                    ),
            );
        }

        if (classType) {
            filtered = filtered.filter((ps) => ps.class_type === classType);
        }

        if (onlyUnseen) {
            filtered = filtered.filter(
                (ps) =>
                    !ps.attendance_dates_current_cycle ||
                    ps.attendance_dates_current_cycle.length === 0,
            );
        }

        return filtered;
    }, [
        modalValues.query,
        modalValues.class_type,
        modalValues.only_unseen,
        planningSheetsList,
    ]);

    const modalPagination = useMemo(() => {
        const total = filteredPlanningSheets.length;
        const perPage = Number(modalValues.number_rows) || 50;
        const lastPage = Math.max(Math.ceil(total / perPage), 1);
        const currentPage = Math.min(Number(modalValues.page) || 1, lastPage);
        const from = total === 0 ? 0 : (currentPage - 1) * perPage + 1;
        const to = Math.min(currentPage * perPage, total);

        return {
            data: filteredPlanningSheets.slice(from > 0 ? from - 1 : 0, to),
            current_page: currentPage,
            last_page: lastPage,
            total,
            per_page: perPage,
            from,
            to,
        };
    }, [filteredPlanningSheets, modalValues.number_rows, modalValues.page]);

    const handleModalTableInputChange = (event) => {
        handleModalInputChange(event);

        if (event.target.name !== "page") {
            setModalInputValue("page", 1);
        }
    };

    const setModalTableInputValue = (name, value) => {
        setModalInputValue(name, value);

        if (name !== "page" && name !== "refresh") {
            setModalInputValue("page", 1);
        }
    };

    useEffect(() => {
        return () => {
            dispatch(clearReport());
        };
    }, [dispatch]);

    useEffect(() => {
        dispatch(startListCycles({ asList: true }));
        dispatch(startListCoordination({ asList: true }));
        dispatch(startListTeachers({ asList: true }));
    }, [dispatch]);

    useEffect(() => {
        if (cycles) {
            dispatch(startShowProgrammaticAdvancesReport(values));
        } else {
            dispatch(clearReport());
        }
    }, [
        cycles,
        coordination_id,
        teacher_id,
        page,
        number_rows,
        query,
        refresh,
    ]);

    const handleExportExcel = () => {
        dispatch(startExportProgrammaticAdvancesReport(values));
    };

    const handleViewAdvances = (item) => {
        setActiveRow(item);
        setModalFormValues(modalDefaultValues, true);
        setShowModal(true);
        dispatch(
            startShowPlanningSheetsList({
                teacherId: item.teacher_id,
                subjectId: item.school_subject_id,
                cycleId: item.cycle_id,
            }),
        );
        dispatch(
            startShowPlanningSheetCriteria(
                {
                    school_subject_id: item.school_subject_id,
                    cycle_id: item.cycle_id,
                    teacher_id: item.teacher_id,
                },
                setCriteriaList,
            ),
        );
    };

    return (
        <CardContainer title="Reporte de avances programáticos">
            <Row>
                <Col md={4}>
                    <SelectSearchMainCyclesApp
                        title="Ciclo"
                        placeholder="Seleccione ciclos"
                        infoText={
                            report?.count > 0 && report?.cycles?.length > 0 ? (
                                <span>
                                    Lista completa de ciclos incluidos{" "}
                                    <TooltipAntdApp
                                        headerContent={
                                            <span>Lista de ciclos</span>
                                        }
                                        bodyContent={
                                            <ul>
                                                {report.cycles.map(
                                                    (cycle, index) => (
                                                        <li key={index}>
                                                            {cycle}
                                                        </li>
                                                    ),
                                                )}
                                            </ul>
                                        }
                                        bodyCenter={false}
                                    >
                                        <div className="fa-solid fa-circle-info fa-lg text-info"></div>
                                    </TooltipAntdApp>
                                </span>
                            ) : (
                                ""
                            )
                        }
                        name="cycles"
                        value={cycles}
                        required
                        onChange={handleReportInputChange}
                        options={orderMainCycles(cyclesList, false)}
                        errorText={errors.cycles && errors.cycles[0]}
                    />
                </Col>
                <Col md={4}>
                    <CoordinationSelectApp
                        coordination_name="coordination_id"
                        coordination_id={coordination_id}
                        handleInputChange={handleReportInputChange}
                        errors={errors}
                    />
                </Col>
                <Col md={4}>
                    <SelectTeachersApp
                        title="Docente"
                        placeholder="Filtrar por docente"
                        name="teacher_id"
                        value={teacher_id}
                        required={false}
                        onChange={handleReportInputChange}
                        options={teachersList.map((t) => ({
                            value: t.id,
                            label: t.username,
                        }))}
                    />
                </Col>
            </Row>

            {cycles && (
                <>
                    <Button
                        type="button"
                        className="btn-app btn-app-green mt-4"
                        onClick={handleExportExcel}
                    >
                        <IconApp iconClassName="fa fa-file-excel me-1" />{" "}
                        Exportar
                    </Button>

                    <style>
                        {`
                        .programmatic-report-table thead th {
                            text-transform: uppercase;
                            font-size: 11px;
                            letter-spacing: 0.5px;
                            padding: 12px 8px !important;
                            border: 1px solid #dee2e6;
                            text-align: center !important;
                            vertical-align: middle !important;
                        }
                        .programmatic-report-table tbody td {
                            border: 1px solid #eee;
                            padding: 10px 8px !important;
                        }
                        .subject-key-badge {
                            background-color: #f0f7ff;
                            color: #1a4b8c;
                            border: 1px solid #d1e6ff;
                            border-radius: 4px;
                            padding: 2px 6px;
                            font-weight: 800;
                            font-size: 11px;
                            display: inline-block;
                            margin-bottom: 4px;
                        }
                        .subject-name-text {
                            font-weight: 500;
                            color: #495057;
                            font-size: 11px;
                        }
                        .teacher-id-text {
                            color: #888;
                            font-size: 10px;
                            font-weight: 600;
                            display: block;
                        }
                        .teacher-name-text {
                            font-weight: 700;
                            color: #333;
                            font-size: 11px;
                        }
                        .group-badge {
                            background-color: #1d3a6d;
                            color: white !important;
                            border-radius: 20px;
                            padding: 4px 12px;
                            font-weight: 700;
                            font-size: 11px;
                            white-space: nowrap;
                            display: inline-block;
                        }
                        .percentage-vistos {
                            font-weight: 800;
                            color: #1d3a6d;
                        }
                        .cycle-text {
                            color: #007bff;
                            font-weight: 700;
                            border: 1px solid #e7f1ff;
                            background-color: #f8fbff;
                            padding: 4px 8px;
                            border-radius: 4px;
                            display: inline-block;
                            white-space: nowrap;
                        }

                        /* Mejoras Móvil */
                        @media (max-width: 768px) {
                            .crud-app__table tbody tr {
                                border: 1px solid #e0e6ed !important;
                                border-radius: 12px !important;
                                margin-bottom: 20px !important;
                                box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06) !important;
                                overflow: hidden !important;
                                display: block !important;
                                background: #fff !important;
                            }
                            .crud-app__table tbody td {
                                border: none !important;
                                padding: 10px 15px !important;
                                display: block !important;
                                width: 100% !important;
                                text-align: left !important;
                            }
                            .crud-app__table tbody td[data-th="Docente"] {
                                background: #5b7da1 !important;
                                color: white !important;
                                padding: 12px 15px !important;
                            }
                            .crud-app__table tbody td[data-th="Docente"] .teacher-id-text,
                            .crud-app__table tbody td[data-th="Docente"] .teacher-name-text {
                                color: white !important;
                            }
                            .crud-app__table tbody td[data-th]:before {
                                content: attr(data-th);
                                font-size: 10px !important;
                                text-transform: uppercase !important;
                                color: #000000 !important;
                                font-weight: 700 !important;
                                display: block !important;
                                border-bottom: 1px solid #f1f5f9 !important;
                                margin-bottom: 6px !important;
                                padding-bottom: 2px !important;
                            }
                            .crud-app__table tbody td[data-th="Docente"]:before {
                                color: #ffffff !important;
                                border-bottom: 1px solid rgba(255, 255, 255, 0.2) !important;
                            }
                            .group-badge, .cycle-text {
                                margin-top: 4px;
                            }
                        }
                        `}
                    </style>

                    <div className="d-flex gap-3 flex-wrap mt-3 text-size-12">
                        <strong>Registros: {report?.count || 0}</strong>
                    </div>

                    <CrudApp
                        crudName="programmatic-advances-report"
                        values={values}
                        setInputValue={setReportInputValue}
                        handleInputChange={handleReportInputChange}
                        pagination={report?.pagination}
                        tableHeaders={[
                            "Docente",
                            "Materia",
                            "Carrera",
                            "Ciclo",
                            "Grupo",
                            "Avances cargados",
                            "Temas vistos",
                            "porcentaje de avances vistos",
                        ]}
                        boldCells
                    >
                        {report?.pagination?.data?.map((item, index) => (
                            <tr key={index} className="text-size-12">
                                <td
                                    data-th="Docente"
                                    className="align-middle text-start p-2"
                                >
                                    <div className="d-flex align-items-center gap-2">
                                        <div
                                            className="rounded-circle bg-primary-subtle d-flex align-items-center justify-content-center"
                                            style={{
                                                width: "35px",
                                                height: "35px",
                                                minWidth: "35px",
                                            }}
                                        >
                                            <span className="text-primary fw-bold text-size-10">
                                                {item.teacher_name
                                                    ?.split(" ")
                                                    .map((n) => n[0])
                                                    .join("")
                                                    .slice(0, 2)
                                                    .toUpperCase()}
                                            </span>
                                        </div>
                                        <div>
                                            <span className="teacher-id-text">
                                                #{item.no_employe || "-"}
                                            </span>
                                            <div className="teacher-name-text text-uppercase">
                                                {item.teacher_name || "-"}
                                            </div>
                                        </div>
                                    </div>
                                </td>
                                <td
                                    data-th="Materia"
                                    className="align-middle text-start"
                                >
                                    <span className="subject-key-badge">
                                        {item.subject_key}
                                    </span>
                                    <div
                                        className="subject-name-text"
                                        style={{ minWidth: "150px" }}
                                    >
                                        {item.subject_name || "-"}
                                    </div>
                                </td>

                                <td
                                    data-th="Carrera"
                                    className="align-middle text-center"
                                >
                                    <div
                                        className="text-size-10 text-muted text-uppercase"
                                        style={{ lineHeight: "1.2" }}
                                    >
                                        {item.curriculum || "-"}
                                    </div>
                                </td>
                                <td
                                    data-th="Ciclo"
                                    className="align-middle text-center"
                                >
                                    <span className="cycle-text text-size-11">
                                        {item.cycle || "-"}
                                    </span>
                                </td>
                                <td
                                    data-th="Grupo"
                                    className="align-middle text-center"
                                >
                                    <a
                                        href={`/app/operators/academicgroups/${item.group_id}`}
                                        target="_blank"
                                        rel="noopener noreferrer"
                                        style={{
                                            textDecoration: "none",
                                        }}
                                        className="group-badge"
                                    >
                                        {item.group || "-"}
                                    </a>
                                </td>
                                <td
                                    data-th="Avances cargados"
                                    className="align-middle text-center"
                                >
                                    {item.programmatic_advances_loaded_count ||
                                        0}
                                </td>
                                <td
                                    data-th="Temas vistos"
                                    className="align-middle text-center"
                                >
                                    {item.programmatic_advances_seen_count || 0}
                                </td>
                                <td
                                    data-th="Porcentaje de avances vistos"
                                    className="align-middle text-center"
                                >
                                    <div className="percentage-vistos">
                                        {item.percentage_seen || 0}%
                                    </div>
                                    <div
                                        className="progress mt-1"
                                        style={{ height: "6px" }}
                                    >
                                        <div
                                            className={`progress-bar ${
                                                (item.percentage_seen || 0) >=
                                                100
                                                    ? "bg-success"
                                                    : (item.percentage_seen ||
                                                            0) >= 50
                                                      ? "bg-primary"
                                                      : "bg-warning"
                                            }`}
                                            role="progressbar"
                                            style={{
                                                width: `${
                                                    item.percentage_seen || 0
                                                }%`,
                                            }}
                                            aria-valuenow={
                                                item.percentage_seen || 0
                                            }
                                            aria-valuemin="0"
                                            aria-valuemax="100"
                                        ></div>
                                    </div>
                                </td>
                                <td
                                    data-th="Acciones"
                                    className="align-middle text-center"
                                >
                                    <IconApp
                                        iconClassName="fas fa-eye mx-2"
                                        description="Ver avances programáticos"
                                        color="#495057"
                                        isClickable={true}
                                        onClick={() => handleViewAdvances(item)}
                                    />
                                </td>
                            </tr>
                        ))}
                    </CrudApp>

                    <ModalApp
                        titleModal={`Avances programáticos cargados: ${activeRow?.subject_name}`}
                        size="xxxl"
                        dialogClassName="planning-sheet-modal"
                        backdrop="static"
                        keyboard={false}
                        openModal={showModal}
                        setModalAction={setShowModal}
                        Action={() => null}
                    >
                        <div className="programmatic-advances-modal">
                            <style>
                                {`
                                    .programmatic-advances-modal #planning-sheet-crud {
                                        margin-top: 0 !important;
                                    }

                                    @media (min-width: 769px) {
                                        .programmatic-advances-modal .crud-app__table-wrapper {
                                            max-height: 68vh;
                                            overflow: auto;
                                        }

                                        .programmatic-advances-modal .crud-app__table {
                                            min-width: 1800px;
                                        }
                                    }
                                `}
                            </style>
                            <ProgrammaticAdvanceTable
                                values={modalValues}
                                setInputValue={setModalTableInputValue}
                                handleInputChange={handleModalTableInputChange}
                                pagination={modalPagination}
                                showEvaluationCriteria={showEvaluationCriteria}
                                criteriaList={criteriaList}
                                readOnly={true}
                            />
                        </div>
                    </ModalApp>
                </>
            )}
        </CardContainer>
    );
}
