import DropDownArrowIcon from "@mui/icons-material/KeyboardArrowDown";
import { Button, ListItemText, Menu, MenuItem } from "@mui/material";
import { getLocalizedString } from "@olenbetong/appframe-core";
import { useState } from "react";
import type { TransportElementsRecord } from "../data/dsTransportElements.js";

export type TransportElementSelectProps = {
	elements: TransportElementsRecord[];
	onSelect: (element: TransportElementsRecord) => void;
};

export function TransportElementSelect({ elements, onSelect }: TransportElementSelectProps) {
	let [anchorEl, setAnchorEl] = useState<HTMLElement | null>(null);
	let open = !!anchorEl;
	let [selected, setSelected] = useState<TransportElementsRecord | null>(null);

	function handleChange(element: TransportElementsRecord) {
		setAnchorEl(null);
		onSelect(element);
		setSelected(element);
	}

	return (
		<>
			<Button
				id="select_element"
				variant="contained"
				endIcon={
					<DropDownArrowIcon
						style={{ transform: open ? "rotate(180deg)" : "rotate(0deg)", transition: "transform 0.2s" }}
					/>
				}
				sx={{ width: "165px" }}
				aria-controls={open ? "basic-menu" : undefined}
				aria-haspopup="true"
				aria-expanded={open ? "true" : undefined}
				onClick={(event) => setAnchorEl(event.currentTarget)}
			>
				{selected ? `${selected.ElementID} - ${selected.Name}` : getLocalizedString("Select element")}
			</Button>
			<Menu id="menu_element" anchorEl={anchorEl} open={open} onClose={() => setAnchorEl(null)}>
				{elements.map((element) => (
					<MenuItem key={element.PrimKey} onClick={() => handleChange(element)}>
						<ListItemText>
							{element.ElementID} - {element.Name}
						</ListItemText>
					</MenuItem>
				))}
			</Menu>
		</>
	);
}
