"use client";
import { useState, useEffect } from "react";
import { useParams, useSearchParams } from "next/navigation";
import { useSessionStore } from "@store/Sesion.Store";
import Location from "@components/Location/Location";
import { useLocationStore } from "@store/Location.Store";
import { useEventHandlerStore, EVENT_TYPES } from "@store/EventHandler.Store";
import AccountCircleOutlinedIcon from "@mui/icons-material/AccountCircleOutlined";
import AutoDeleteIcon from "@mui/icons-material/AutoDeleteOutlined";
import dayjs from "dayjs";
import "dayjs/locale/es";
import TextTime from "@core/app/components/TextTime/TextTime";
import TextDate from "@core/app/components/TextDate/TextDate";
import { useAlert } from "@store/Alert.Store";
import { useNavigation } from "@hooks/goto";
import { createScheduleDisabled } from "../../../Collaborators.Service";
import MaterialAlert from "@mui/material/Alert";

dayjs.locale("es");

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

export default function DiscountCreate() {
    const data = useParams<UrlData>();
    const id = data.id;
    const cid = data.cid;
    const searchParams = useSearchParams();
    const cname = searchParams.get("cname");
    const alert = useAlert();
    const SessionInfo = useSessionStore();
    const location = useLocationStore();
    const eventHandler = useEventHandlerStore();
    const { goTo } = useNavigation();
    const [dateFromDay, setDateFromDay] = useState<dayjs.Dayjs>(dayjs().startOf("day"));
    const [dateFromTime, setDateFromTime] = useState<dayjs.Dayjs>(dayjs().hour(8).startOf("hour"));
    const [dateToDay, setDateToDay] = useState<dayjs.Dayjs>(dayjs().startOf("day"));
    const [dateToTime, setDateToTime] = useState<dayjs.Dayjs>(dayjs().hour(20).startOf("hour"));

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

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

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

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

        location.add({
            url: "",
            title: "Crear",
            icon: <AutoDeleteIcon sx={{ fontSize: "32px", mr: "10px" }} />,
        });
    }, []);

    useEffect(() => {
        if (eventHandler.eventType === EVENT_TYPES.SAVE) {
            const dateFromData = dayjs(
                dateFromDay.format("YYYY-MM-DD") + " " + dateFromTime.format("HH:mm:ss")
            );
            const dateToData = dayjs(dateToDay.format("YYYY-MM-DD") + " " + dateToTime.format("HH:mm:ss"));

            createScheduleDisabled({
                employeeId: cid,
                companyId: id,
                startDate: dateFromData.toDate(),
                endDate: dateToData.toDate(),
                sessionUser: SessionInfo.userId,
            })
                .then(() => {
                    alert.showSuccess(`La restricción ha sido creada`);
                    eventHandler.setEventType(EVENT_TYPES.SLEEP);
                    setTimeout(() => {
                        goTo("/admin/org/profile/" + id + "/collaborators/" + cid + "/disabled");
                    }, 2000);
                })
                .catch((error) => {
                    alert.showError(error.format());
                    eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
                });
        }
    }, [eventHandler.eventType]);

    return (
        <>
            <Location />

            <MaterialAlert
                severity="info"
                sx={{
                    marginTop: "10px",
                    maxWidth: "680px",
                    marginLeft: "auto",
                    marginRight: "auto",
                }}
            >
                <strong>Atención:</strong> El periodo de tiempo cargado hará que el colaborador no pueda
                recibir turnos durante el mismo.
            </MaterialAlert>

            <div
                style={{
                    display: "flex",
                    flexDirection: "row",
                    justifyContent: "center",
                    gap: "10px",
                    marginTop: "15px",
                }}
            >
                <div>
                    <TextDate
                        placeholder="Desde"
                        selectedDate={dateFromDay}
                        onChange={(value: dayjs.Dayjs) => {
                            setDateFromDay(value);
                        }}
                    />
                </div>
                <div>
                    <TextTime
                        placeholder="&nbsp;"
                        width="100%"
                        timeFraction={1}
                        value={dateFromTime}
                        onChange={setDateFromTime}
                    />
                </div>
            </div>

            <div
                style={{
                    display: "flex",
                    flexDirection: "row",
                    justifyContent: "center",
                    gap: "10px",
                    marginTop: "15px",
                }}
            >
                <div>
                    <TextDate
                        placeholder="Hasta"
                        selectedDate={dateToDay}
                        onChange={(value: dayjs.Dayjs) => {
                            setDateToDay(value);
                        }}
                    />
                </div>
                <div>
                    <TextTime
                        placeholder="&nbsp;"
                        width="100%"
                        timeFraction={1}
                        value={dateToTime}
                        onChange={setDateToTime}
                    />
                </div>
            </div>

            <div style={{ marginTop: "15px" }}></div>
        </>
    );
}
