'use client';

import * as React from 'react';
import { useEffect, useState } from 'react';
import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';
import Card from '@mui/material/Card';
import CardContent from '@mui/material/CardContent';
import Box from '@mui/material/Box';
import Divider from '@mui/material/Divider';
import Avatar from '@mui/material/Avatar';
import Chip from '@mui/material/Chip';
import { formatDistanceToNow } from 'date-fns';

import { config } from '@/config';
import { fetchAdminNotifications, AdminNotification } from '@/services/notifications.service';
import { AppLoader } from '@/components/core/app-loader';

function useNotifications() {
  const [notifications, setNotifications] = useState<AdminNotification[]>([]);
  const [loading, setLoading] = useState<boolean>(true);

  useEffect(() => {
    async function fetchNotifications() {
      try {
        setLoading(true);
        const response = await fetchAdminNotifications();
        if (response.success) {
          setNotifications(response.data.notifications);
        }
      } catch (error) {
        console.error('Failed to fetch notifications:', error);
      } finally {
        setLoading(false);
      }
    }
    fetchNotifications();
  }, []);

  return { notifications, loading };
}

function getNotificationColor(type: string) {
  switch (type) {
    case 'order':
      return 'primary';
    case 'user':
      return 'secondary';
    case 'event':
      return 'success';
    case 'payment':
      return 'warning';
    case 'system':
      return 'info';
    default:
      return 'default';
  }
}

export default function Page(): React.JSX.Element {
  const { notifications, loading } = useNotifications();

  return (
    <Stack spacing={3}>
      <div>
        <Typography variant="h4">Notifications</Typography>
      </div>
      
      <Card>
        <CardContent>
          <Typography variant="h6" sx={{ mb: 2 }}>
            All Notifications
          </Typography>
          
          <Stack spacing={2}>
            {loading ? (
              <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: 300, width: '100%' }}>
                <AppLoader size="md" compact label="Loading notifications..." />
              </Box>
            ) : (
              notifications.map((notification, index) => (
                <Box key={notification._id}>
                  <Box
                    sx={{
                      display: 'flex',
                      alignItems: 'flex-start',
                      gap: 2,
                      p: 2,
                      borderRadius: 1,
                      backgroundColor: notification.isRead ? 'transparent' : 'action.hover',
                      '&:hover': {
                        backgroundColor: 'action.hover'
                      }
                    }}
                  >
                    <Avatar
                      src={notification.relatedData?.url || '/assets/default-avatar.png'}
                      sx={{ width: 40, height: 40 }}
                    />
                    <Box sx={{ flex: 1, minWidth: 0 }}>
                      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 1 }}>
                        <Typography variant="subtitle2" sx={{ fontWeight: 600 }}>
                          {notification.title}
                        </Typography>
                        <Chip
                          label={notification.type}
                          size="small"
                          color={getNotificationColor(notification.type) as any}
                          variant="outlined"
                        />
                        {!notification.isRead && (
                          <Box
                            sx={{
                              width: 8,
                              height: 8,
                              borderRadius: '50%',
                              backgroundColor: 'primary.main'
                            }}
                          />
                        )}
                      </Box>
                      <Typography variant="body2" color="text.secondary" sx={{ mb: 1 }}>
                        {notification.message}
                      </Typography>
                      <Typography variant="caption" color="text.secondary">
                        {formatDistanceToNow(new Date(notification.createdAt), { addSuffix: true })}
                      </Typography>
                    </Box>
                  </Box>
                  {index < notifications.length - 1 && <Divider />}
                </Box>
              ))
            )}
          </Stack>
        </CardContent>
      </Card>
    </Stack>
  );
}