import { memo, useCallback, useEffect, useState } from "react"
import { MessageInfo } from "./types"
import { userInteractionInternals } from "./userInteraction"
import { Snackbar, Alert } from "@mui/material"

const ShowMessage = memo(() => {
  const [messageInfo, setMessageInfo] = useState<MessageInfo>()

  useEffect(() => {
    userInteractionInternals.showMessage = setMessageInfo
    return () => (userInteractionInternals.showMessage = undefined)
  }, [setMessageInfo])

  const handleMessageClose = useCallback(
    (_event?: React.SyntheticEvent | Event, reason?: string) => {
      if (reason === "clickaway") {
        return
      }
      setMessageInfo(undefined)
    },
    [setMessageInfo],
  )

  if (messageInfo === undefined) {
    return null
  }

  return (
    <Snackbar open={true} autoHideDuration={messageInfo.duration || 6000} onClose={handleMessageClose}>
      <Alert onClose={handleMessageClose} severity={messageInfo.color} sx={{ width: "100%" }}>
        {messageInfo.content}
      </Alert>
    </Snackbar>
  )
})

export default ShowMessage
