import * as stylex from "@stylexjs/stylex";
import { type PropsWithChildren, type ReactNode, memo } from "react";
import { Drawer } from "vaul";

import VisuallyHidden from "./VisuallyHidden";
import { blackAlpha, color, fontSize, padding, size } from "./tokens.stylex";

export interface BottomDrawerProps extends PropsWithChildren {
	screenReaderTitle: ReactNode;
	trigger: ReactNode;
}

const styles = stylex.create({
	overlay: {
		position: "fixed",
		inset: 0,
		backgroundColor: blackAlpha.blackAlpha40,
	},
	title: {
		fontSize: fontSize.h5,
		fontWeight: 400,
	},
	content: {
		display: "flex",
		position: "fixed",
		flexDirection: "column",

		outline: "none",

		right: 0,
		bottom: 0,
		left: 0,

		marginTop: size.rem16,
		height: "auto",
		maxHeight: "70vh",
		// overflowY: "auto",

		backgroundColor: color.gray600,

		borderTopLeftRadius: size.px2,
		borderTopRightRadius: size.px2,

		padding: size.px4,
		paddingBottom: padding.minBottom4,
	},
	handle: {
		marginBottom: size.rem5,
		marginTop: size.rem1,
		backgroundColor: color.white900,
	},
});

/**
 * This component should be lazy-loaded because it uses some heavy components.
 */
export default memo(function BottomDrawer({
	screenReaderTitle,
	trigger,
	children,
}: BottomDrawerProps) {
	return (
		<Drawer.Root>
			<Drawer.Trigger asChild>{trigger}</Drawer.Trigger>
			<Drawer.Portal>
				<Drawer.Overlay {...stylex.props(styles.overlay)} />
				<Drawer.Content {...stylex.props(styles.content)}>
					<Drawer.Handle {...stylex.props(styles.handle)} />
					<VisuallyHidden>
						<Drawer.Title {...stylex.props(styles.title)}>
							{screenReaderTitle}
						</Drawer.Title>
					</VisuallyHidden>
					{children}
				</Drawer.Content>
			</Drawer.Portal>
		</Drawer.Root>
	);
});
