"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 EventAvailableOutlinedIcon from "@mui/icons-material/EventAvailableOutlined";
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 {
    deleteSchedulesOverrides,
    getSchedulesOverrides,
    findCollaboratorsById,
} from "../../Collaborators.Service";
import dayjs from "dayjs";
import "dayjs/locale/es";
import { ISchedulesOverrides } from "@core/Models/SchedulesOverrides";
import { useNavigation } from "@hooks/goto";
import { useBottomToolbarStore } from "@core/Store/BottomToolbar.Store";
import ButtonMaterial from "@mui/material/Button";
import MaterialAlert from "@mui/material/Alert";
import { CompanyEmployeesView } from "@core/Models/Collaborators.model";


dayjs.locale("es");

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

export default function CollaboratorOverrides() {
    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 [overrides, setOverrides] = useState<ISchedulesOverrides[]>([]);
    const [collaborator, setCollaborator] = useState<CompanyEmployeesView>();

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

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

    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: "Excepciones",
            icon: <EventAvailableOutlinedIcon sx={{ fontSize: "32px", mr: "10px" }} />,
        });
    }, [collaborator]);

    useEffect(() => {
        loadOverrides();
    }, [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();
        };
    }, [overrides, collaborator]);

    const loadCollaborator = () => {
        findCollaboratorsById({ id: cid })
            .then((data) => {
                if (data) setCollaborator(data);
            });
    };

    const loadOverrides = () => {
        eventHandler.setEventType(EVENT_TYPES.LOADING);
        getSchedulesOverrides({
            companyId: id,
            employeeId: cid,
        })
            .then((items) => {
                if (items === null) {
                    return;
                }
                setOverrides(items);
            })
            .catch((error) => {
                alert.showError(error.format());
            })
            .finally(() => {
                eventHandler.setEventType(EVENT_TYPES.SLEEP);
            });
    };

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

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

    return (
        <>
            <Location />
            <MaterialAlert
                severity="info"
                sx={{
                    marginTop: "10px",
                    maxWidth: "680px",
                    marginLeft: "auto",
                    marginRight: "auto",
                }}
            >
                <strong>Excepciones de horario:</strong> Las fechas configuradas a continuación reemplazarán
                el horario habitual del colaborador. Resulta útil para feriados o días especiales donde el profesional
                decide trabajar en otro horario o no trabajar (si se definen sin horarios activos).
            </MaterialAlert>
            <div style={{ display: "flex", flexDirection: "column", marginTop: "20px", gap: "10px", maxWidth: "680px", marginLeft: "auto", marginRight: "auto" }}>
                {overrides.map((item, index) => (
                    <div key={index} style={{
                        display: 'flex',
                        flexDirection: 'row',
                        justifyContent: 'space-between',
                        alignItems: 'center',
                        padding: '10px',
                        border: '1px solid #ccc',
                        borderRadius: '5px',
                        backgroundColor: '#fff'
                    }}>
                        <div style={{ display: 'flex', flexDirection: 'column' }}>
                            <strong style={{ fontSize: '1.1rem' }}>{dayjs(item.date).format("dddd DD [de] MMMM, YYYY")}</strong>
                            {(!item.schedules || item.schedules.length === 0) ? (
                                <span style={{ color: '#EF4444' }}>Sin horarios disponibles</span>
                            ) : (
                                <span>
                                    {item.schedules.map(sch => (
                                        <span key={String(sch.from)} style={{ marginRight: '10px', color: sch.disabled ? '#EF4444' : '#4b43bdff' }}>
                                            {sch.disabled ? <s>{String(sch.from)} - {String(sch.to)}</s> : `${String(sch.from)} - ${String(sch.to)}`}
                                        </span>
                                    ))}
                                </span>
                            )}
                        </div>
                        <ButtonMaterial
                            variant="outlined"
                            color="error"
                            size="small"
                            onClick={() => {
                                confirm.show(
                                    "¿Está seguro que desea eliminar esta excepción?",
                                    () => {
                                        handleDeleteItem(item._id || item.id || "");
                                    },
                                    () => {}
                                );
                            }}
                        >
                            Eliminar
                        </ButtonMaterial>
                    </div>
                ))}
            </div>

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