import { MenuItem, Select, Typography } from "@mui/material";
import { AccountIconWidget } from "../AccountIconWidget";
import { useAccounts } from "../../hooks/AccountsListProvider";
import { AmountWidget } from "../AmountWidget";

export function AccountInput(p: {
  value?: number;
  onChange: (value: number) => void;
  label?: string;
  style?: React.CSSProperties;
}): React.ReactElement {
  const accounts = useAccounts();
  let current = p.value;
  if (!current && accounts.list.list.length > 0) {
    current = (accounts.list.default ?? accounts.list.list[0]).id;
    p.onChange(current);
  }

  return (
    <Select
      value={current}
      label={p.label ?? ""}
      onChange={(e) => p.onChange(Number(e.target.value))}
      size="small"
      style={p.style}
    >
      {accounts.list.list.map((a) => (
        <MenuItem value={a.id}>
          <span
            style={{
              display: "inline-flex",
              alignItems: "center",
              height: "100%",
            }}
          >
            <AccountIconWidget account={a} />
            <span
              style={{
                marginLeft: "1em",
                display: "flex",
                flexDirection: "column",
              }}
            >
              <span>{a.name}</span>
              <Typography variant="caption">
                <AmountWidget amount={a.balance} />
              </Typography>
            </span>
          </span>
        </MenuItem>
      ))}
    </Select>
  );
}
