// 单选下拉框, 是input还是text还是其他由children决定

import * as React from "react";
import Menu from "@mui/material/Menu";
import MenuItem from "@mui/material/MenuItem";
import CheckIcon from "@mui/icons-material/Check";
import { ThemeProvider, createTheme } from "@mui/material/styles";
import triangle from "@/assets/project/triangle.svg";

type IOption = {
	label: string;
	value: string;
};

type IMyMenuProps = {
	children: React.ReactNode;
	options: Array<IOption>;
	value: string;
	setValue?: any;
	hasTriangle?: boolean;
};

const theme = createTheme({
	components: {
		MuiMenu: {
			styleOverrides: {
				root: {
					overflow: "overlay",
				},
			},
		},
		MuiMenuItem: {
			styleOverrides: {
				root: {
					fontSize: "14px",
					lineHeight: "36px",
					display: "flex",
					justifyContent: "space-between",
					":hover": {
						color: "rgba(19, 112, 255, 1)",
					},
					"&.Mui-selected": {
						backgroundColor: "#fff",
						color: "rgba(19, 112, 255, 1)",
					},
				},
			},
		},
		MuiList: {
			styleOverrides: {
				root: {
					maxHeight: "268px",
				},
			},
		},
		MuiSvgIcon: {
			styleOverrides: {
				root: {
					width: "16px",
					height: "16px",
				},
			},
		},
	},
});

const MyMenu = (props: IMyMenuProps) => {
	const { children, options, value, setValue, hasTriangle = false } = props;
	const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);
	const open = Boolean(anchorEl);
	const handleClick = (event: React.MouseEvent<HTMLDivElement>) => {
		setAnchorEl(event.currentTarget);
	};
	const handleClose = (value: string) => {
		setAnchorEl(null);
	};

	const handleMenuClick = (value: string) => {
		setValue && setValue(value);
		setAnchorEl(null);
	};

	return (
		<ThemeProvider theme={theme}>
			<div>
				<div
					onClick={handleClick}
					style={{
						display: "flex",
						justifyContent: "flex-start",
						alignItems: "center",
					}}
				>
					{children}
					{hasTriangle && (
						<img
							style={{
								width: "16px",
								height: "16px",
								transform: open ? "rotateX(180deg)" : "",
							}}
							src={triangle}
							alt=""
						/>
					)}
				</div>
				<Menu
					id="basic-menu"
					anchorEl={anchorEl}
					open={open}
					onClose={handleClose}
					MenuListProps={{
						"aria-labelledby": "basic-button",
					}}
				>
					{options.map((option, index) => {
						return (
							<MenuItem
								onClick={() => handleMenuClick(option.value)}
								selected={value === option.value}
								key={index}
							>
								<span>{option.label}</span>
								{value === option.value && (
									<CheckIcon sx={{ marginLeft: "12px" }} />
								)}
							</MenuItem>
						);
					})}
				</Menu>
			</div>
		</ThemeProvider>
	);
};

export default MyMenu;
