import { MenuItem, Select, SelectChangeEvent } from "@mui/material";
import { Movement } from "../../api/MovementsApi";
import { MovementWidget } from "../MovementWidget";

export function MovementSelect(p: {
  list: Movement[];
  value: Movement | undefined;
  onChange: (value: Movement | undefined) => void;
}): React.ReactElement {
  const handleChange = (event: SelectChangeEvent) => {
    if (!event.target.value) {
      p.onChange(undefined);
      return;
    }
    const id = Number(event.target.value);
    p.onChange(p.list.find((m) => m.id === id));
  };

  return (
    <Select value={p.value?.id.toString()} onChange={handleChange}>
      <MenuItem value={undefined}>
        <i>None</i>
      </MenuItem>
      {p.list.map((l) => (
        <MenuItem key={l.id} value={l.id.toString()}>
          <MovementWidget movement={l} />
        </MenuItem>
      ))}
    </Select>
  );
}
