import {
  Button,
  Dialog,
  DialogActions,
  DialogContent,
  DialogContentText,
  DialogTitle,
  FormControlLabel,
  ListItem,
  ListItemIcon,
  ListItemText,
  Radio,
  RadioGroup,
} from "@mui/material";
import React from "react";
import { Account } from "../api/AccountApi";
import { useAccounts } from "../hooks/AccountsListProvider";
import { AccountIconWidget } from "../widgets/AccountIconWidget";
import { AmountWidget } from "../widgets/AmountWidget";

export function SelectAccountDialog(p: {
  open: boolean;
  onClose: () => void;
  onSelected: (c: Account) => void;
  title: string;
  description: string | React.ReactElement;
  confirmButton?: string;
  excludedAccounts?: Account[];
}): React.ReactElement {
  const accounts = useAccounts();

  const [choice, setChoice] = React.useState<Account | null>(
    accounts.list.default
  );

  const submit = () => {
    if (choice) p.onSelected(choice);
  };

  return (
    <Dialog
      open={p.open}
      onClose={() => {
        p.onClose();
      }}
    >
      <DialogTitle>{p.title}</DialogTitle>
      <DialogContent dividers>
        <DialogContentText>{p.description}</DialogContentText>

        <RadioGroup>
          {accounts.list.list.map((option) => (
            <FormControlLabel
              value={option.id}
              key={option.id}
              control={
                <Radio
                  disabled={
                    p.excludedAccounts?.find((a) => a.id === option.id) !==
                    undefined
                  }
                  checked={option.id === choice?.id}
                  onChange={() => {
                    setChoice(option);
                  }}
                />
              }
              label={
                <ListItem>
                  <ListItemIcon>
                    <AccountIconWidget account={option} />
                  </ListItemIcon>
                  <ListItemText
                    primary={option.name}
                    secondary={<AmountWidget amount={option.balance} />}
                  />
                </ListItem>
              }
            />
          ))}
        </RadioGroup>
      </DialogContent>
      <DialogActions>
        <Button
          onClick={() => {
            p.onClose();
          }}
        >
          Cancel
        </Button>
        <Button onClick={submit} autoFocus disabled={choice === null}>
          {p.confirmButton ?? "Submit"}
        </Button>
      </DialogActions>
    </Dialog>
  );
}
