"use client";
import { useParams } from "next/navigation";
import Location from "@components/Location/Location";
import { useLocationStore } from "@store/Location.Store";
import { useSessionStore } from "@store/Sesion.Store";
import { useEventHandlerStore, EVENT_TYPES } from "@store/EventHandler.Store";
import AccountCircleOutlinedIcon from "@mui/icons-material/AccountCircleOutlined";
import AutoDeleteIcon from "@mui/icons-material/AutoDeleteOutlined";
import MoreTimeIcon from "@mui/icons-material/MoreTime";
import { useAlert } from "@store/Alert.Store";
import { useConfirmStore } from "@store/Confirm.Store";
import { useEffect, useState } from "react";
import { deleteScheduleDisabled, findSchedulesDisabledByCollaborator } from "../../Collaborators.Service";
import dayjs from "dayjs";
import "dayjs/locale/es";
import { SchedulesDisabledByCollaboratorView } from "@core/Models/SchedulesDisabled";
import { useNavigation } from "@hooks/goto";
import { useBottomToolbarStore } from "@core/Store/BottomToolbar.Store";
import ButtonMaterial from "@mui/material/Button";
import TimeMarker from "@core/app/components/TimeMarker/TimeMarker";
import MaterialAlert from "@mui/material/Alert";

dayjs.locale("es");

type UrlData = {
    id: string;
    cid: string;
};

export default function CollaboratorDisabled() {
    const data = useParams<UrlData>();
    const id = data.id;
    const cid = data.cid;
    const SessionInfo = useSessionStore();
    const eventHandler = useEventHandlerStore();
    const location = useLocationStore();
    const confirm = useConfirmStore();
    const alert = useAlert();
    const { goTo } = useNavigation();
    const bottomToolbar = useBottomToolbarStore();

    const [disabledItems, setDisabledItems] = useState<SchedulesDisabledByCollaboratorView>();

    useEffect(() => {
        eventHandler.setEventType(EVENT_TYPES.SLEEP);
    }, []);

    useEffect(() => {
        location.clear();

        if (!disabledItems) {
            return;
        }

        location.add({
            url: "/admin/org/profile/" + id + "/collaborators",
            title: "Colaboradores",
            icon: null,
        });

        location.add({
            url: "/admin/org/profile/" + id + "/collaborators" + "/" + cid,
            title: disabledItems.employeeFullName,
            icon: <AccountCircleOutlinedIcon sx={{ mr: 0.5 }} fontSize="inherit" />,
        });

        location.add({
            url: "/admin/org/profile/" + id + "/collaborators",
            title: "Restricciones",
            icon: <AutoDeleteIcon sx={{ fontSize: "32px", mr: "10px" }} />,
        });
    }, [disabledItems]);

    useEffect(() => {
        loadDisabledSchedules();
    }, [id, cid]);

    useEffect(() => {
        bottomToolbar.set(
            <div
                style={{
                    display: "flex",
                    justifyContent: "center",
                    alignItems: "center",
                    flexDirection: "row",
                    fontWeight: "bold",
                    color: "var(--white)",
                    padding: "10px",
                    width: "100%",
                    fontSize: "22px",
                    paddingRight: "50px",
                }}
            >
                <ButtonMaterial
                    variant="text"
                    startIcon={<MoreTimeIcon />}
                    sx={{ color: "var(--white)" }}
                    onClick={() => {
                        handleAddItem();
                    }}
                >
                    Nuevo
                </ButtonMaterial>
            </div>
        );

        return () => {
            bottomToolbar.clear();
        };
    }, [disabledItems]);

    const loadDisabledSchedules = () => {
        eventHandler.setEventType(EVENT_TYPES.LOADING);
        findSchedulesDisabledByCollaborator({
            companyId: id,
            employeeId: cid,
            sessionUser: SessionInfo.userId,
        })
            .then((items) => {
                if (items === null) {
                    return;
                }
                setDisabledItems(items);
            })
            .catch((error) => {
                alert.showError(error.format());
            })
            .finally(() => {
                eventHandler.setEventType(EVENT_TYPES.SLEEP);
            });
    };

    const handleAddItem = () => {
        eventHandler.setEventType(EVENT_TYPES.SLEEP);
        if (!disabledItems) {
            return;
        }
        goTo(
            "/admin/org/profile/" +
                id +
                "/collaborators/" +
                cid +
                "/disabled/new?cname=" +
                encodeURIComponent(disabledItems.employeeFullName)
        );
    };

    const handleDeleteItem = (itemId: string) => {
        eventHandler.setEventType(EVENT_TYPES.LOADING);
        deleteScheduleDisabled({
            companyId: id,
            id: itemId,
            sessionUser: SessionInfo.userId,
        })
            .catch((error) => {
                alert.showError(error.format());
            })
            .finally(() => {
                loadDisabledSchedules();
            });
    };

    return (
        <>
            <Location />
            <MaterialAlert
                severity="info"
                sx={{
                    marginTop: "10px",
                    maxWidth: "680px",
                    marginLeft: "auto",
                    marginRight: "auto",
                }}
            >
                <strong>Atención:</strong> Los periodos de tiempo listados abajo son los que se encuentran
                deshabilitados para el colaborador. Esto significa que no se le asignarán turnos durante estos
                periodos de tiempo.
            </MaterialAlert>
            <div style={{ display: "flex", flexDirection: "column", marginTop: "20px", gap: "10px" }}>
                {disabledItems?.disabledItems.map((item, index) => (
                    <TimeMarker
                        key={index}
                        start={dayjs(item.startDate)}
                        end={dayjs(item.endDate)}
                        startColor={"#4b43bdff"}
                        endColor={"#EF4444"}
                        onLongPress={() => {
                            confirm.show(
                                "¿Está seguro que desea eliminar esta restricción?",
                                () => {
                                    handleDeleteItem(item._id);
                                },
                                () => {}
                            );
                        }}
                    />
                ))}
            </div>

            <div style={{ marginBottom: "10px" }}>&nbsp;</div>
        </>
    );
}
