import Box from "@mui/material/Box";
import Alert from "@mui/material/Alert";
import * as React from "react";
import { useEffect, useState } from "react";
import PropTypes from "prop-types";

// Error box shows on top of screen for 3 seconds, if error msg is not empty
export default function ErrorBox(props) {
  const { severity, error = "", setError } = props;
  const [show, setShow] = useState(false);

  useEffect(() => {
    if (error === "") {
      setShow(false);
      return;
    }
    setShow(true);
    const timeId = setTimeout(() => {
      // After 3 seconds set the show value to false
      setError("")
    }, 3000);

    return () => {
      clearTimeout(timeId);
    };
  }, [error, setError]);

  if (!show) {
    return null;
  }

  return (
    <Box
      sx={{
        display: "flex",
        width: "100%",
        justifyContent: "center",
        position: "fixed",
        mt: 6,
        zIndex: 2,
      }}
    >
      <Alert severity={severity}>{error}</Alert>
    </Box>
  );
}

ErrorBox.propTypes = {
  severity: PropTypes.string.isRequired,
  // error message
  error: PropTypes.string.isRequired,
  // error state handler
  setError: PropTypes.func.isRequired,
};
