"use client";
import { useParams } from "next/navigation";
import style from "./ClientLayout.module.css";
import { useEffect, useState, Suspense } from "react";
import Avatar from "@components/Avatar/Avatar";
import { useSessionStore } from "@store/Sesion.Store";
import SectionContainer from "@components/SectionContainer/SectionContainer";
import { useAlert } from "@store/Alert.Store";
import { EVENT_TYPES, useEventHandlerStore } from "@store/EventHandler.Store";
import Secure from "@components/Secure/Secure";
import { deleteClient, findClientById } from "./Client.Service";
import { OrganizationClientView } from "@core/Models/Clients.model";
import SettingsIcon from "@mui/icons-material/Settings";
import IconButton from "@mui/material/IconButton";
import DeleteIcon from "@mui/icons-material/Delete";

import { useMenuStore } from "@core/Store/Menu.Store";
import { Badge, BadgeProps } from "@mui/material";
import Menu from "@core/app/components/Menu/Menu";
import styled from "@emotion/styled";
import Content from "@core/app/components/Content/Content";
import SuspenseLoading from "@core/app/components/SuspendeLoading/SuspenseLoading";
import { useConfirmStore } from "@core/Store/Confirm.Store";
import { useNavigation } from "@core/app/hooks/goto";

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

const StyledBadge = styled(Badge)<BadgeProps>(() => ({
    "& .MuiBadge-badge": {
        right: 5,
        top: 13,
        padding: "0 4px",
    },
}));

export default function ClientDashboardLayout({
    children,
}: {
    children: React.ReactNode;
}) {
    const data = useParams<UrlData>();
    const oid = data.oid;
    const clientId = data.clientId;
    const SessionInfo = useSessionStore();
    const alert = useAlert();
    const confirm = useConfirmStore();
    const eventHandler = useEventHandlerStore();
    const menu = useMenuStore();
    const { goTo } = useNavigation();

    const [client, setClient] = useState<OrganizationClientView | null>(null);
    const [clientName, setClientName] = useState<string>("");
    const [, setClientEmail] = useState<string>("");
    const [clientAvatar, setClientAvatar] = useState<string>("");

    useEffect(() => {
        createMenu();
    }, []);

    useEffect(() => {
        loadClientData();
    }, [SessionInfo.userId]);

    const createMenu = () => {
        menu.clear();

        menu.add({
            text: "Eliminar Cliente",
            onClick: () => {
                eliminarCliente();
            },
            icon: <DeleteIcon />,
        });
    };

    const eliminarCliente = () => {
        confirm.show(
            "Atención: Al eliminar un cliente se perderá la información relacionada con él, como por ejemplo sus reservas. Estas seguro que quieres eliminar el cliente?",
            () => {
                eventHandler.setEventType(EVENT_TYPES.LOADING);
                deleteClient({
                    clientId: clientId,
                    sessionUser: SessionInfo.userId,
                })
                    .then(() => {
                        alert.showSuccess("El cliente fue eliminado con éxito");
                        goTo("/admin/org/profile/" + oid + "/clients");
                    })
                    .catch((error) => {
                        alert.showError(error.format());
                    })
                    .finally(() => {
                        eventHandler.setEventType(EVENT_TYPES.SLEEP);
                    });
            },
            () => {}
        );
    };

    const loadClientData = () => {
        if (!SessionInfo.loged) {
            return;
        }

        eventHandler.setEventType(EVENT_TYPES.LOADING);

        findClientById({
            id: clientId,
            companyId: oid,
            sessionUser: SessionInfo.userId,
        })
            .then((client) => {
                setClient(client);
                setClientName(client.fullName);
                setClientEmail(client.email);
                setClientAvatar(client.avatar);
            })
            .catch((error) => {
                alert.showError(error.format());
            })
            .finally(() => {
                eventHandler.setEventType(EVENT_TYPES.SLEEP);
            });
    };

    return (
        <>
            <Content>
                <Suspense fallback={<SuspenseLoading />}>
                    <Secure>
                        <SectionContainer style={{ top: "70px" }}>
                            <div className={style.clientProfileHeader}>
                                <Avatar
                                    name="userProfileAvatar"
                                    src={clientAvatar}
                                    alt={clientName}
                                />
                                <div>
                                    <h1>{clientName}</h1>
                                    <span>{client?.email}</span>
                                </div>
                            </div>
                            <div
                                className={style.clientProfileOptionsContainer}
                            >
                                {children}
                            </div>
                            <div
                                style={{
                                    position: "absolute",
                                    top: "-40px",
                                    right: "40px",
                                }}
                            >
                                <div className={style.buttonMenu}>
                                    {menu.length() > 0 && (
                                        <StyledBadge
                                            color="warning"
                                            badgeContent="1"
                                            variant="dot"
                                            sx={{
                                                top: "-10px",
                                            }}
                                        >
                                            <IconButton
                                                sx={{ color: "var(--white)" }}
                                                id="button-menu-appointment"
                                                aria-controls={
                                                    menu.visible
                                                        ? "tx-menu"
                                                        : undefined
                                                }
                                                aria-expanded={
                                                    menu.visible
                                                        ? "true"
                                                        : undefined
                                                }
                                                aria-haspopup="true"
                                                onClick={() => {
                                                    menu.setAnchorEl(
                                                        document.getElementById(
                                                            "button-menu-appointment"
                                                        )!
                                                    );
                                                    menu.show();
                                                }}
                                            >
                                                <SettingsIcon />
                                            </IconButton>
                                        </StyledBadge>
                                    )}
                                </div>
                            </div>
                            <Menu />
                        </SectionContainer>
                    </Secure>
                </Suspense>
            </Content>
        </>
    );
}
