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

import useMediaQuery from "@mui/material/useMediaQuery";
import { useTheme } from "@mui/material/styles";
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";
import Toolbar from "@mui/material/Toolbar";

export default function MultiOptionDialog(props) {
  const { dialog: dialogProp, onClose, open, ...other } = props;
  const [value, setValue] = useState(dialogProp.current);
  const [dialog, setDialog] = useState(dialogProp);
  const theme = useTheme();
  const fullScreen = useMediaQuery(theme.breakpoints.down("sm"));
  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
      TransitionProps={{ onEntering: handleEntering }}
      open={open}
      {...other}
      sx={
        fullScreen
          ? {}
          : { "& .MuiDialog-paper": { width: "80%", maxHeight: 435 } }
      }
      fullScreen={fullScreen}
    >
      <Toolbar sx={{ display: { sm: "none" } }} />
      <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>
  );
}
