"use client";
import { useState, useEffect } from "react";
import { useParams } 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 ClientsIcon from "@mui/icons-material/AccountBoxOutlined";
import IconButton from "@mui/material/IconButton";
import DeleteIcon from "@mui/icons-material/Delete";

import { useAlert } from "@store/Alert.Store";

import { useConfirmStore } from "@core/Store/Confirm.Store";
import HeaderConfProvider from "@core/app/components/HeaderConfProvider/HeaderConfProvider";
import { deleteRepeat, getRepeatsByClient } from "../Client.Service";
import { DeleteRepeatsParams, FindRepeatsParams, RepeatView } from "@core/Models/Repeats.model";

import style from "./repeats.module.css";

type UrlData = {
    oid: string;
    clientId: string;
};

export default function ClientCreate() {
    const data = useParams<UrlData>();
    const id = data.oid;
    const clientId = data.clientId;
    const alert = useAlert();
    const confirm = useConfirmStore();
    const SessionInfo = useSessionStore();
    const location = useLocationStore();
    const eventHandler = useEventHandlerStore();

    const [repeats, setRepeats] = useState<RepeatView[]>([]);

    useEffect(() => {
        eventHandler.setEventType(EVENT_TYPES.SLEEP);

        if (!id) {
            return;
        }

        if (!clientId) {
            return;
        }

        loadRepeats();
    }, [id, clientId]);

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

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

        location.add({
            url: "/admin/org/" + id + "/client/" + clientId + "/profile",
            title: "Perfil",
            icon: <ClientsIcon sx={{ mr: 0.5 }} fontSize="inherit" />,
        });

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

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

    const loadRepeats = () => {
        const data: FindRepeatsParams = {
            companyId: id,
            clientId: clientId,
        };

        eventHandler.setEventType(EVENT_TYPES.LOADING);

        getRepeatsByClient(data)
            .then((repeats) => {
                setRepeats(repeats);
            })
            .finally(() => {
                eventHandler.setEventType(EVENT_TYPES.NEED_ADD);
            });
    };

    const handleDelete = (id: string) => {
        if (!SessionInfo.userId) {
            return;
        }

        if (!id) {
            return;
        }

        const data: DeleteRepeatsParams = {
            repeatId: id,
            sessionUser: SessionInfo.userId,
        };

        eventHandler.setEventType(EVENT_TYPES.LOADING);

        deleteRepeat(data)
            .then(() => {
                loadRepeats();
            })
            .catch((error) => {
                alert.showError(error.format());
            })
            .finally(() => {
                eventHandler.setEventType(EVENT_TYPES.NEED_ADD);
            });
    };

    return (
        <>
            <Location />
            <HeaderConfProvider />
            <div style={{ marginTop: "15px" }}></div>
            <div
                style={{
                    display: "flex",
                    flexDirection: "column",
                    gap: "10px",
                    marginTop: "20px",
                }}
            >
                {repeats.map((repeat) => {
                    return (
                        <div
                            key={repeat.id}
                            className={style.cardRepeat}
                            style={{
                                backgroundColor: repeat.employeeCalendarColor,
                                display: "flex",
                                flexDirection: "row",
                                justifyContent: "space-between",
                            }}
                        >
                            <div>
                                <h3>
                                    Todos los {repeat.weekDayName} a las {repeat.startHourFormatted}
                                </h3>
                                <h1>{repeat.serviceName}</h1>
                                <h2>con {repeat.employeeName}</h2>
                            </div>
                            <div>
                                <IconButton
                                    aria-label="delete"
                                    sx={{ color: "var(--white)" }}
                                    onClick={() => {
                                        confirm.show(
                                            "Estas seguro que queres eliminar la repeticion?",
                                            () => {
                                                handleDelete(repeat.id);
                                            },
                                            () => {}
                                        );
                                    }}
                                >
                                    <DeleteIcon />
                                </IconButton>
                            </div>
                        </div>
                    );
                })}
            </div>
            <div style={{ marginTop: "15px" }}></div>
        </>
    );
}
