// components/NotificationModal.tsx
"use client";

import { useState, useEffect } from "react";
import {
  Box,
  Modal,
  Typography,
  Button,
  List,
  ListItem,
  ListItemText,
  IconButton,
  Badge,
} from "@mui/material";
import CloseIcon from "@mui/icons-material/Close";

interface Notification {
  message: string;
  recipient: string;
  createdAt: Date;
  _id: string;
}

export default function NotificationModal({
  userEmail,
}: {
  userEmail: string | null;
}) {
  const [notifications, setNotifications] = useState<Notification[]>([]);
  const [isOpen, setIsOpen] = useState(false);
  const [hasShown, setHasShown] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchNotifications = async () => {
      if (userEmail && !hasShown) {
        setLoading(true);
        try {
          const response = await fetch(
            `/api/notify/getUserNotification?email=${encodeURIComponent(
              userEmail
            )}`
          );

          if (!response.ok) {
            throw new Error("Failed to fetch notifications");
          }

          const data = await response.json();

          const formattedNotifications: Notification[] = data.map((n: any) => ({
            message: n.message,
            recipient: n.recipient,
            createdAt: new Date(n.createdAt),
            _id: String(n._id),
          }));

          setNotifications(formattedNotifications);
          setError(null);

          if (formattedNotifications.length > 0) {
            setIsOpen(true);
            setHasShown(true);
          }
        } catch (err) {
          console.error("Error fetching notifications:", err);
          setError("Failed to load notifications");
        } finally {
          setLoading(false);
        }
      }
    };

    fetchNotifications();
  }, [userEmail, hasShown]);

  const handleClose = () => {
    setIsOpen(false);
  };

  return (
    <Modal
      open={isOpen}
      onClose={handleClose}
      aria-labelledby="notification-modal-title"
      sx={{
        display: "flex",
        alignItems: "flex-end",
        justifyContent: "flex-end",
      }}
    >
      <Box
        sx={{
          position: "absolute",
          bottom: "20px",
          right: "20px",
          width: 400,
          maxWidth: "90vw",
          bgcolor: "background.paper",
          boxShadow: 24,
          p: 3,
          borderRadius: 2,
          maxHeight: "60vh",
          overflowY: "auto",
        }}
      >
        <Box
          display="flex"
          justifyContent="space-between"
          alignItems="center"
          mb={2}
        >
          <Typography id="notification-modal-title" variant="h6" component="h2">
            Notifications
            {notifications.length > 0 && (
              <Badge
                badgeContent={notifications.length}
                color="primary"
                sx={{ ml: 2 }}
              />
            )}
          </Typography>
          <IconButton onClick={handleClose}>
            <CloseIcon />
          </IconButton>
        </Box>

        {loading ? (
          <Typography textAlign="center" py={4}>
            Loading...
          </Typography>
        ) : error ? (
          <Typography color="error" textAlign="center" py={4}>
            {error}
          </Typography>
        ) : notifications.length > 0 ? (
          <List>
            {notifications.map((notification) => (
              <ListItem
                key={notification._id}
                sx={{ borderBottom: "1px solid #eee" }}
              >
                <ListItemText
                  primary={notification.message}
                  secondary={new Date(notification.createdAt).toLocaleString()}
                />
              </ListItem>
            ))}
          </List>
        ) : (
          <Typography
            variant="body1"
            color="text.secondary"
            textAlign="center"
            py={4}
          >
            No new notifications
          </Typography>
        )}

        <Box mt={2} display="flex" justifyContent="flex-end">
          <Button variant="contained" onClick={handleClose}>
            Close
          </Button>
        </Box>
      </Box>
    </Modal>
  );
}
