import { useEffect, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import { Badge, Button, Dropdown, List, Typography, Empty, Space, theme } from 'antd';
import { BellOutlined, CheckOutlined } from '@ant-design/icons';
import { useSocialStore } from '@/stores/social.store';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';

dayjs.extend(relativeTime);

const TYPE_ICONS: Record<string, string> = {
  friend_request: '\uD83E\uDD1D',
  friend_accepted: '\uD83C\uDF89',
  poke: '\uD83D\uDC4B',
  comment: '\uD83D\uDCAC',
  upload_approved: '\u2705',
  upload_rejected: '\u274C',
  achievement: '\uD83C\uDFC6',
  system: '\u2139\uFE0F',
};

export default function NotificationBell() {
  const navigate = useNavigate();
  const { token } = theme.useToken();
  const { unreadNotificationCount, notifications, fetchUnreadCount, fetchNotifications, markNotificationRead, markAllNotificationsRead } = useSocialStore();
  const pollRef = useRef<ReturnType<typeof setInterval>>(undefined);

  // Poll for unread count — 2 min fallback (SSE handles real-time delivery)
  useEffect(() => {
    fetchUnreadCount();
    pollRef.current = setInterval(fetchUnreadCount, 120_000);
    return () => clearInterval(pollRef.current);
  }, [fetchUnreadCount]);

  const handleOpenChange = (open: boolean) => {
    if (open) {
      fetchNotifications(1);
    }
  };

  const items = notifications.slice(0, 10);

  const dropdownContent = (
    <div style={{
      background: token.colorBgElevated,
      borderRadius: 8,
      border: `1px solid ${token.colorBorder}`,
      width: 340,
      maxHeight: 420,
      overflow: 'auto',
    }}>
      <div style={{
        display: 'flex',
        justifyContent: 'space-between',
        alignItems: 'center',
        padding: '8px 12px',
        borderBottom: `1px solid ${token.colorBorder}`,
      }}>
        <Typography.Text strong>Notifications</Typography.Text>
        {unreadNotificationCount > 0 && (
          <Button
            type="link"
            size="small"
            icon={<CheckOutlined />}
            onClick={(e) => { e.stopPropagation(); markAllNotificationsRead(); }}
          >
            Mark all read
          </Button>
        )}
      </div>

      {items.length === 0 ? (
        <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="No notifications" style={{ padding: '20px 0' }} />
      ) : (
        <List
          dataSource={items}
          renderItem={(n) => (
            <List.Item
              style={{
                padding: '8px 12px',
                cursor: 'pointer',
                background: n.isRead ? undefined : 'rgba(52, 152, 219, 0.08)',
              }}
              onClick={() => {
                if (!n.isRead) markNotificationRead(n.id);
              }}
            >
              <Space>
                <span style={{ fontSize: 18 }}>{TYPE_ICONS[n.type] || '\uD83D\uDD14'}</span>
                <div>
                  <Typography.Text strong={!n.isRead} style={{ fontSize: 13, display: 'block' }}>
                    {n.title}
                  </Typography.Text>
                  <Typography.Text type="secondary" style={{ fontSize: 12 }}>
                    {n.message}
                  </Typography.Text>
                  <br />
                  <Typography.Text type="secondary" style={{ fontSize: 11 }}>
                    {dayjs(n.createdAt).fromNow()}
                  </Typography.Text>
                </div>
              </Space>
            </List.Item>
          )}
        />
      )}

      <div
        style={{
          textAlign: 'center',
          padding: '8px',
          borderTop: `1px solid ${token.colorBorder}`,
          cursor: 'pointer',
        }}
        onClick={() => navigate('/volunteer/notifications')}
      >
        <Typography.Text type="secondary" style={{ fontSize: 13 }}>See all notifications</Typography.Text>
      </div>
    </div>
  );

  return (
    <Dropdown
      dropdownRender={() => dropdownContent}
      trigger={['click']}
      placement="bottomRight"
      onOpenChange={handleOpenChange}
    >
      <Badge count={unreadNotificationCount} size="small" offset={[-2, 2]}>
        <Button
          type="text"
          size="small"
          icon={<BellOutlined style={{ color: '#fff', fontSize: 16 }} />}
          style={{ minWidth: 32, minHeight: 32, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}
        />
      </Badge>
    </Dropdown>
  );
}
