import { useState, useRef, useEffect } from "react";

import Button from "@mui/material/Button";
import DialogTitle from "@mui/material/DialogTitle";
import DialogContent from "@mui/material/DialogContent";
import DialogActions from "@mui/material/DialogActions";
import Dialog from "@mui/material/Dialog";
import RadioGroup from "@mui/material/RadioGroup";
import Radio from "@mui/material/Radio";
import FormControlLabel from "@mui/material/FormControlLabel";

export default function MultiOptionDialog(props) {
  const { dialog: dialogProp, onClose, open, ...other } = props;
  const [value, setValue] = useState(dialogProp.current);
  const [dialog, setDialog] = useState(dialogProp);

  const radioGroupRef = useRef(null);

  useEffect(() => {
    setDialog(dialogProp);
    setValue(dialogProp.current);
  }, [dialogProp, open]);

  const handleEntering = () => {
    if (radioGroupRef.current != null) radioGroupRef.current.focus();
  };

  const handleCancel = () => onClose();

  const handleOk = () => onClose(value, dialog.onSelect);

  const handleChange = (e) => {
    setValue(e.target.value);
  };

  return (
    <Dialog
      sx={{ "& .MuiDialog-paper": { width: "80%", maxHeight: 435 } }}
      maxWidth="xs"
      TransitionProps={{ onEntering: handleEntering }}
      open={open}
      {...other}
    >
      <DialogTitle>{dialog.title}</DialogTitle>
      <DialogContent dividers>
        <RadioGroup
          ref={radioGroupRef}
          aria-label={dialogProp.title}
          name={dialog.title}
          value={value}
          onChange={handleChange}
        >
          {dialog.options.map((option) => (
            <FormControlLabel
              value={option}
              key={option}
              control={<Radio />}
              label={option}
            />
          ))}
        </RadioGroup>
      </DialogContent>
      <DialogActions>
        <Button autoFocus onClick={handleCancel}>
          Cancel
        </Button>
        <Button onClick={handleOk}>Ok</Button>
      </DialogActions>
    </Dialog>
  );
}
