import CloseOutlined from "@mui/icons-material/CloseOutlined";
import Drawer from "@mui/material/Drawer";
import { IconButton } from "@/shared/ui/IconButton.jsx";

export function SideDrawer({
    actions,
    as: Component = "section",
    children,
    className = "",
    contentClassName = "",
    drawerProps = {},
    onClose,
    open,
    title,
    width = "default",
    ...props
}) {
    const widthClassName =
        width === "wide" ? "side-drawer--wide" : width === "detail" ? "side-drawer--detail" : "";
    const drawerClassName = ["side-drawer", widthClassName, className]
        .filter(Boolean)
        .join(" ");
    const backdropSlotProps = drawerProps.slotProps?.backdrop || {};
    const resolvedDrawerProps = {
        ...drawerProps,
        slotProps: {
            ...drawerProps.slotProps,
            backdrop: {
                ...backdropSlotProps,
                // 抽屉需要保留父页面上下文，使用全局半透明遮罩 token，避免 MUI 默认遮罩过暗。
                sx: [
                    { backgroundColor: "var(--overlay-scrim)" },
                    ...(Array.isArray(backdropSlotProps.sx) ? backdropSlotProps.sx : [backdropSlotProps.sx].filter(Boolean)),
                ],
            },
        },
    };

    return (
        <Drawer anchor="right" open={open} onClose={onClose} {...resolvedDrawerProps}>
            <Component className={drawerClassName} {...props}>
                <div className="side-drawer__header">
                    {title ? <h2 className="side-drawer__title">{title}</h2> : <span />}
                    {onClose ? (
                        <IconButton label="关闭" onClick={onClose}>
                            <CloseOutlined fontSize="small" />
                        </IconButton>
                    ) : null}
                </div>
                <div className={["side-drawer__body", contentClassName].filter(Boolean).join(" ")}>{children}</div>
                {actions ? <div className="side-drawer__actions">{actions}</div> : null}
            </Component>
        </Drawer>
    );
}
