"use client";
import { useParams, useSearchParams } 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 EventAvailableOutlinedIcon from "@mui/icons-material/EventAvailableOutlined";
import AccountCircleOutlinedIcon from "@mui/icons-material/AccountCircleOutlined";
import { useAlert } from "@store/Alert.Store";
import { useConfirmStore } from "@store/Confirm.Store";
import { useEffect, useState } from "react";
import MaterialAlert from "@mui/material/Alert";
import { ScheduleItem } from "@core/Models/Collaborators.model";
import { createSchedulesOverrides } from "../../../Collaborators.Service";
import { Grid2 } from "@mui/material";
import TextTime from "@core/app/components/TextTime/TextTime";
import TextDate from "@core/app/components/TextDate/TextDate";
import ScheduleItemRow from "@components/ScheduleItemRow/ScheduleItemRow";
import Button from "@core/app/components/Button/Button";
import dayjs from "dayjs";
import "dayjs/locale/es";
import { useNavigation } from "@hooks/goto";

dayjs.locale("es");

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

interface SchedulesDateItem {
    from: dayjs.Dayjs;
    to: dayjs.Dayjs;
    data: ScheduleItem;
}

export default function OverridesCreate() {
    const data = useParams<UrlData>();
    const id = data.id;
    const cid = data.cid;
    const searchParams = useSearchParams();
    const cname = searchParams.get("cname");
    const SessionInfo = useSessionStore();
    const eventHandler = useEventHandlerStore();
    const location = useLocationStore();
    const confirm = useConfirmStore();
    const alert = useAlert();
    const { goTo } = useNavigation();

    const [overrideDate, setOverrideDate] = useState<dayjs.Dayjs>(dayjs(new Date()).startOf("day"));
    const [from, setFrom] = useState<dayjs.Dayjs>(dayjs(new Date()).hour(8).minute(0));
    const [to, setTo] = useState<dayjs.Dayjs>(dayjs(new Date()).hour(12).minute(0));
    const [schedules, setSchedules] = useState<Array<SchedulesDateItem>>([]);

    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 + "/overrides",
            title: "Excepciones",
            icon: <EventAvailableOutlinedIcon sx={{ mr: 0.5 }} fontSize="inherit" />,
        });

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

    useEffect(() => {
        if (eventHandler.eventType === EVENT_TYPES.SAVE) {
            const dateToSave = overrideDate.toDate();
            
            createSchedulesOverrides({
                companyId: id,
                employeeId: cid,
                date: dateToSave,
                schedules: getSchedulesToSave(),
                sessionUser: SessionInfo.userId,
            })
                .then(() => {
                    alert.showSuccess("Excepción de horario creada");
                    eventHandler.setEventType(EVENT_TYPES.SLEEP);
                    setTimeout(() => {
                        goTo("/admin/org/profile/" + id + "/collaborators/" + cid + "/overrides");
                    }, 2000);
                })
                .catch((error) => {
                    alert.showError(error.format());
                    eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
                });
        }
    }, [eventHandler.eventType]);

    const getSchedulesToSave = (): ScheduleItem[] => {
        return schedules.map((schedule) => {
            return {
                from: schedule.from.format("HH:mm"),
                to: schedule.to.format("HH:mm"),
                disabled: schedule.data.disabled || false,
            };
        });
    };

    const addButtonHandler = () => {
        const newSchedule: SchedulesDateItem = {
            from: from.clone(),
            to: to.clone(),
            data: {
                from: from.format("HH:mm"),
                to: to.format("HH:mm"),
                disabled: false,
            },
        };

        const hasOverlap = schedules.some((schedule) => {
            const existingFrom = dayjs(schedule.from);
            const existingTo = dayjs(schedule.to);
            return newSchedule.from.isBefore(existingTo) && newSchedule.to.isAfter(existingFrom);
        });

        if (hasOverlap) {
            alert.showError(
                "El horario se solapa con uno existente. Por favor, elige otro horario."
            );
        } else if (newSchedule.from.isAfter(newSchedule.to)) {
            alert.showError("La hora de inicio debe ser anterior a la hora de fin.");
        } else {
            setSchedules([...schedules, newSchedule]);
            eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
        }
    };

    const deleteScheduleHandler = (from: string) => {
        confirm.show(
            "¿Estas seguro que queres eliminar el horario?",
            () => {
                const filteredSchedules = schedules.filter(
                    (schedule) => schedule.data.from != from
                );
                setSchedules(filteredSchedules);
                eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
            },
            () => { }
        );
    };

    const checkChangeHandler = (from: string, data: boolean) => {
        const newSchedules = schedules.map((schedule) => {
            if (schedule.data.from == from) {
                return {
                    ...schedule,
                    data: {
                        ...schedule.data,
                        disabled: data,
                    },
                };
            }
            return schedule;
        });

        setSchedules(newSchedules);
        eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
    };

    return (
        <>
            <Location />
            <div
                style={{ display: "flex", flexDirection: "column", marginTop: "20px", gap: "10px", maxWidth: "680px", marginLeft: "auto", marginRight: "auto" }}
            >
                <div style={{ marginBottom: "15px" }}>
                    <TextDate
                        placeholder="Fecha de la Excepción"
                        selectedDate={overrideDate}
                        onChange={(date) => {
                            setOverrideDate(date);
                            eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
                        }}
                    />
                </div>
                
                <Grid2 container sx={{ marginTop: "0px" }}>
                    <Grid2 size={3}>
                        <TextTime
                            placeholder="Desde"
                            width="100%"
                            value={from}
                            onChange={setFrom}
                        />
                    </Grid2>
                    <Grid2 size={1}></Grid2>
                    <Grid2 size={3}>
                        <TextTime placeholder="Hasta" width="100%" value={to} onChange={setTo} />
                    </Grid2>
                    <Grid2 size={1}></Grid2>
                    <Grid2
                        size={4}
                        sx={{ display: "flex", justifyContent: "center", alignItems: "end" }}
                    >
                        <Button
                            text="Agregar Horario"
                            width="100%"
                            color="primary"
                            style={{ height: "42px" }}
                            onClick={addButtonHandler}
                        />
                    </Grid2>
                </Grid2>

                {schedules.map((schedule, index) => (
                    <ScheduleItemRow
                        key={index}
                        from={schedule.data.from}
                        to={schedule.data.to}
                        disabled={schedule.data.disabled}
                        onCheckChange={checkChangeHandler}
                        onDelete={deleteScheduleHandler}
                    />
                ))}

                {schedules.length < 1 && (
                    <MaterialAlert sx={{ width: "100%" }} severity="warning">
                        <strong>Atención:</strong> Si guardas esta excepción sin cargar ningún horario, 
                        el colaborador no tendrá turnos disponibles en todo el día, reemplazando su horario normal.
                    </MaterialAlert>
                )}
            </div>

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