import React, { useEffect, useState } from "react";
import { Dialog, DialogTitle, DialogContent, Button, Typography } from "@mui/material";
import PropTypes from "prop-types";

function RoleChangedPopup({ open, onLogout, message = "", countdown = 5 }) {
  const [seconds, setSeconds] = useState(countdown);
  const [localMessage, setLocalMessage] = useState("");

  useEffect(() => {
    setLocalMessage(localStorage.getItem("ErrorMessage"));
    if (!open) return;
    setSeconds(countdown);
    const interval = setInterval(() => {
      setSeconds((s) => s - 1);
    }, 1000);
    return () => clearInterval(interval);
  }, [open, countdown]);

  useEffect(() => {
    if (seconds === 0 && open) {
      onLogout();
    }
  }, [seconds, open, onLogout]);

  return (
    <Dialog open={open}>
      <DialogTitle>{localMessage}</DialogTitle>
      <DialogContent>
        <Typography>
           You will be logged out automatically in {seconds} seconds.
        </Typography>
        <Button variant="contained" color="primary" onClick={onLogout} sx={{ mt: 2 }}>
          Logout Now
        </Button>
      </DialogContent>
    </Dialog>
  );
}

RoleChangedPopup.propTypes = {
  open: PropTypes.bool.isRequired,
  onLogout: PropTypes.func.isRequired,
  message: PropTypes.string,
  countdown: PropTypes.number,
};

export default RoleChangedPopup;
