"use client";
import style from "./UserProfile.module.css";
import Avatar from "@components/Avatar/Avatar";
import { useSessionStore } from "@store/Sesion.Store";
import SectionContainer from "@components/SectionContainer/SectionContainer";
import { uploadAvatar } from "./UserAvatar.Service";
import { useAlert } from "@store/Alert.Store";
import { EVENT_TYPES, useEventHandlerStore } from "@store/EventHandler.Store";
import { ApiError } from "@models/Server.Error.model";
import SettingsIcon from "@mui/icons-material/Settings";
import IconButton from "@mui/material/IconButton";
import { Badge, BadgeProps } from "@mui/material";
import styled from "@emotion/styled";
import Secure from "@components/Secure/Secure";
import Content from "@core/app/components/Content/Content";
import { Suspense, useEffect, useState } from "react";
import { SystemNotificationsProvider } from "@core/app/components/SystemNotificationsProvider/SystemNotificationsProvider";
import SuspenseLoading from "@core/app/components/SuspendeLoading/SuspenseLoading";
import { useMenuStore } from "@core/Store/Menu.Store";
import Menu from "@core/app/components/Menu/Menu";

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

export default function DashboardLayout({ children }: { children: React.ReactNode }) {
    const SessionInfo = useSessionStore();
    const alert = useAlert();
    const eventHandler = useEventHandlerStore();
    const menu = useMenuStore();

    const [userAvatar, setUserAvatar] = useState("");

    const handleAvatarChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        e.preventDefault();

        const file = e.target.files?.[0];

        if (!file) {
            return;
        }

        const formData = new FormData();
        formData.append("sessionUser", SessionInfo.userId); // Añade el ID del usuario
        formData.append("file", file);

        uploadAvatar(formData)
            .then((res) => {
                if (res.success) {
                    alert.showSuccess("Avatar actualizado");
                }
            })
            .catch((error: ApiError) => {
                alert.showError(error.format());
            })
            .finally(() => {
                eventHandler.setEventType(EVENT_TYPES.SLEEP);
            });
    };

    useEffect(() => {
        if (!SessionInfo.userId) {
            return;
        }
        setUserAvatar(SessionInfo.avatar);
    }, [SessionInfo.userId]);
    return (
        <>
            <SystemNotificationsProvider />
            <Content>
                <Suspense fallback={<SuspenseLoading />}>
                    <Secure>
                        <SectionContainer style={{ top: "70px" }}>
                            <div className={style.userProfileHeader}>
                                <Avatar
                                    name="userProfileAvatar"
                                    src={userAvatar}
                                    alt="Avatar"
                                    readOnly={false}
                                    onChange={handleAvatarChange}
                                />
                                <div>
                                    <h1>{SessionInfo.userFullName}</h1>
                                    <span>{SessionInfo.userEmail}</span>
                                </div>
                            </div>
                            <div className={style.userProfileOptionsContainer}>{children}</div>
                            {menu.length() > 0 && (
                                <div style={{ position: "absolute", top: "-40px", right: "40px" }}>
                                    <div className={style.buttonMenu}>
                                        <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>
        </>
    );
}
