import { useUnit } from 'effector-react'
import { Snackbar, Alert, Stack, IconButton } from '@mui/material'
import CloseIcon from '@mui/icons-material/Close'
import { $notifications, dismissNotification as dismissNotificationEvent } from '../../model/notification'

export function NotificationStack() {
  const notifications = useUnit($notifications)
  const dismissNotification = useUnit(dismissNotificationEvent)

  if (notifications.length === 0) return null

  return (
    <Stack
      spacing={1}
      sx={{
        position: 'fixed',
        bottom: 80,
        left: '50%',
        transform: 'translateX(-50%)',
        zIndex: 2000,
        width: 'auto',
        maxWidth: 400,
      }}
    >
      {notifications.map((n) => (
        <Snackbar
          key={n.id}
          open
          autoHideDuration={n.autoHideDuration}
          onClose={() => dismissNotification(n.id)}
          anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
        >
          <Alert
            severity={n.type}
            variant="filled"
            action={
              <IconButton size="small" color="inherit" onClick={() => dismissNotification(n.id)}>
                <CloseIcon fontSize="small" />
              </IconButton>
            }
          >
            {n.message}
          </Alert>
        </Snackbar>
      ))}
    </Stack>
  )
}
