"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 SchedulesIcon from "@mui/icons-material/AccessTime";
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 { CollaboratorSchedulesView, ScheduleItem } from "@core/Models/Collaborators.model";
import {
    findCollaboratorsSchedules,
    updateCollaboratorsSchedules,
} from "../../Collaborators.Service";
import WeekDaySelector from "@core/app/components/WeekDaySelector/WeekDaySelector";
import { Grid2 } from "@mui/material";
import TextTime from "@core/app/components/TextTime/TextTime";
import ScheduleItemRow from "@components/ScheduleItemRow/ScheduleItemRow";
import Button from "@core/app/components/Button/Button";
import dayjs from "dayjs";
import "dayjs/locale/es";

dayjs.locale("es");

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

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

export default function CollaboratorSchedules() {
    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 [collaborator, setCollaborator] = useState<CollaboratorSchedulesView>();
    const [weekDay, setWeekDay] = useState(1);
    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.SLEEP);
    }, []);

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

        if (!collaborator) {
            return;
        }

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

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

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

    useEffect(() => {
        loadCollaboratorSchedules();
    }, [weekDay]);

    useEffect(() => {
        if (eventHandler.eventType === EVENT_TYPES.SAVE) {
            updateCollaboratorsSchedules({
                companyId: id,
                employeeId: cid,
                weekDay: weekDay,
                schedules: getSchedulesToSave(),
                sessionUser: SessionInfo.userId,
            })
                .then(() => {
                    alert.showSuccess("Disponibilidad actualizada");
                })
                .catch((error) => {
                    alert.showError(error.format());
                })
                .finally(() => {
                    eventHandler.setEventType(EVENT_TYPES.SLEEP);
                });
        }
    }, [eventHandler.eventType]);

    const loadCollaboratorSchedules = () => {
        eventHandler.setEventType(EVENT_TYPES.LOADING);
        findCollaboratorsSchedules({
            companyId: id,
            employeeId: cid,
            weekDay: weekDay,
        })
            .then((collaborator) => {
                if (collaborator === null) {
                    return;
                }
                setCollaborator(collaborator);
                setSchedulesFromServer(collaborator.schedules);
                setFrom(dayjs(new Date()).hour(8).minute(0));
                setTo(dayjs(new Date()).hour(12).minute(0));
                eventHandler.setEventType(EVENT_TYPES.SLEEP);
            })
            .catch((error) => {
                alert.showError(error.format());
            })
            .finally(() => {
                eventHandler.setEventType(EVENT_TYPES.SLEEP);
            });
    };

    const setSchedulesFromServer = (schedules: ScheduleItem[]) => {
        setSchedules(
            schedules.map((schedule) => {
                const dataFrom = schedule.from.split(":");
                const fromHoras = parseInt(dataFrom[0]);
                const fromMinutos = parseInt(dataFrom[1]);

                const dataTo = schedule.to.split(":");
                const toHoras = parseInt(dataTo[0]);
                const toMinutos = parseInt(dataTo[1]);

                return {
                    from: dayjs(new Date()).hour(fromHoras).minute(fromMinutos),
                    to: dayjs(new Date()).hour(toHoras).minute(toMinutos),
                    data: schedule,
                };
            })
        );
    };

    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,
            },
        };

        // Función para verificar si el horario se solapa con alguno existente
        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 {
            // Agregar el horario si no hay solapamiento
            setSchedules([...schedules, newSchedule]);
            eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
        }
    };

    const weekDayChangeHandler = (day: number) => {
        if (eventHandler.eventType === EVENT_TYPES.NEED_SAVE) {
            confirm.show(
                "Si no guardas los cambios se perderán. Estas seguro que queres cambiar el dia?",
                () => {
                    setWeekDay(day);
                },
                () => {
                    setWeekDay(weekDay);
                }
            );
        } else {
            setWeekDay(day);
        }
    };

    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 updateItem = schedules.find((schedule) => schedule.data.from == from);
        if (updateItem) {
            updateItem.data.disabled = data;
        }

        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" }}
            >
                <WeekDaySelector value={weekDay} onChange={weekDayChangeHandler} />
                <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"
                            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="info">
                        <strong>No hay horarios creados:</strong> para que los clientes puedan
                        realizar una reserva con este colaborador en el día seleccionado debe tener
                        cargada su disponibilidad para cada día de la semana.
                    </MaterialAlert>
                )}
            </div>

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