"use client";
import { useState, useEffect } from "react";
import { useParams } from "next/navigation";
import style from "./Schedules.module.css";
import Location from "@components/Location/Location";
import { useLocationStore } from "@store/Location.Store";
import { useEventHandlerStore, EVENT_TYPES } from "@store/EventHandler.Store";
import { useAlert } from "@core/Store/Alert.Store";
import { useSessionStore } from "@store/Sesion.Store";
import StorefrontOutlinedIcon from "@mui/icons-material/StorefrontOutlined";
import { disableSchedule, enableSchedule, loadSchedulesEnabled } from "../Org.Service";
import WeekInput from "@core/app/components/WeekInput/WeekInput";
import dayjs from "dayjs";
import "dayjs/locale/es";
import weekday from "dayjs/plugin/weekday";
import "dayjs/locale/es";
import { SchedulesEnabledView } from "@models/SchedulesEnabled.type";
import Avatar from "@components/Avatar/Avatar";
import Button from "@core/app/components/Button/Button";
import { useConfirmStore } from "@core/Store/Confirm.Store";

dayjs.extend(weekday);
dayjs.locale("es");

type UrlData = {
    id: string;
};

export default function Schedules() {
    const data = useParams<UrlData>();
    const id = data.id;
    const location = useLocationStore();
    const eventHandler = useEventHandlerStore();
    const SessionInfo = useSessionStore();
    const alert = useAlert();
    const confirm = useConfirmStore();
    const [startDate, setStartDate] = useState<dayjs.Dayjs>(dayjs().weekday(0));
    const [collaborators, setCollaborators] = useState<SchedulesEnabledView[]>([]);

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

        location.add({
            url: "/admin/org",
            title: "Organizaciones",
            icon: null,
        });

        location.add({
            url: "/admin/org/profile/" + id,
            title: "Organización",
            icon: <StorefrontOutlinedIcon sx={{ mr: 0.5 }} fontSize="inherit" />,
        });

        location.add({
            url: "",
            title: "Horarios Habilitados",
            icon: null,
        });
    }, []);

    useEffect(() => {
        loadCollaborators();
    }, [startDate]);

    const loadCollaborators = async () => {
        eventHandler.setEventType(EVENT_TYPES.LOADING);
        loadSchedulesEnabled({
            companyId: id,
            startDate: startDate.format("YYYY-MM-DD"),
            endDate: startDate.clone().add(6, "d").format("YYYY-MM-DD"),
        })
            .then((res) => {
                setCollaborators(res);
            })
            .finally(() => {
                eventHandler.setEventType(EVENT_TYPES.SLEEP);
            });
    };

    const enable = (collaborator: SchedulesEnabledView) => {
        eventHandler.setEventType(EVENT_TYPES.LOADING);
        enableSchedule({
            companyId: id,
            employees: [{ employeeId: collaborator.employeeId }],
            startDate: startDate.format("YYYY-MM-DD"),
            endDate: startDate.clone().add(6, "d").format("YYYY-MM-DD"),
            sessionUser: SessionInfo.userId,
        })
            .then(() => {
                loadCollaborators();
                alert.showSuccess("Horario habilitado");
            })
            .finally(() => {
                eventHandler.setEventType(EVENT_TYPES.SLEEP);
            });
    };

    const disable = (collaborator: SchedulesEnabledView) => {
        confirm.show(
            "Si continua se deshabilitarán las reservas en el periodo seleccionado. ¿Desea anular las reservas de " +
                collaborator.employeeFullName +
                " para este periodo?",
            () => {
                eventHandler.setEventType(EVENT_TYPES.LOADING);
                disableSchedule({
                    companyId: id,
                    employees: [{ employeeId: collaborator.employeeId }],
                    startDate: startDate.format("YYYY-MM-DD"),
                    endDate: startDate.clone().add(6, "d").format("YYYY-MM-DD"),
                    sessionUser: SessionInfo.userId,
                })
                    .then(() => {
                        loadCollaborators();
                        alert.showSuccess("Horario anulado");
                    })
                    .finally(() => {
                        eventHandler.setEventType(EVENT_TYPES.SLEEP);
                    });
            },
            () => {
                return;
            }
        );
    };

    return (
        <>
            <Location />
            <div
                style={{ display: "flex", flexDirection: "column", marginTop: "20px", gap: "10px" }}
            >
                <WeekInput setStartDate={setStartDate} />

                {collaborators.map((collaborator) => (
                    <div
                        className={style.collaboratorItem}
                        key={"collaborator." + collaborator.employeeId}
                    >
                        <Avatar
                            src={collaborator.employeeAvatar}
                            name="avatar"
                            size="super-small"
                            border="none"
                            alt={collaborator.employeeFullName}
                            style={{ minWidth: "32px" }}
                        />
                        <span className={style.collaboratorName}>
                            {collaborator.employeeFullName}
                        </span>

                        {collaborator.enabled && (
                            <Button
                                text="Anular"
                                width="custom"
                                color="secondary"
                                style={{ minWidth: "100px" }}
                                onClick={() => disable(collaborator)}
                            />
                        )}

                        {!collaborator.enabled && (
                            <Button
                                text="Habilitar"
                                width="custom"
                                color="success"
                                style={{ minWidth: "100px" }}
                                onClick={() => enable(collaborator)}
                            />
                        )}
                    </div>
                ))}
            </div>
        </>
    );
}
