import { Badge, Button, Dropdown, Empty, Space, Typography } from 'antd';
import { IconBell } from '@tabler/icons-react';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { notificationApi, UserNotificationRow } from '@/api/notification';
import { GRAY, COLOR_PRIMARY, RADIUS, SHADOW } from '@/theme/tokens';

const { Text } = Typography;

/**
 * MainLayout 우측 상단 알림 벨.
 * 미읽음 카운트 빨간 dot + Dropdown 최근 10개 리스트.
 */
export default function NotificationBell() {
  const qc = useQueryClient();

  const { data: count = 0 } = useQuery({
    queryKey: ['notifications', 'unread-count'],
    queryFn: notificationApi.unreadCount,
    refetchInterval: 30_000,
  });

  const { data: page } = useQuery({
    queryKey: ['notifications', 'list'],
    queryFn: () => notificationApi.list({ pageSize: 10 }),
  });

  const notifications = page?.list ?? [];

  const handleRead = async (id: number) => {
    await notificationApi.markRead(id);
    qc.invalidateQueries({ queryKey: ['notifications'] });
  };

  const handleReadAll = async () => {
    await notificationApi.markAllRead();
    qc.invalidateQueries({ queryKey: ['notifications'] });
  };

  const overlay = (
    <div style={{
      width: 340,
      background: '#fff',
      borderRadius: RADIUS.lg,
      boxShadow: SHADOW.lg,
      border: `1px solid ${GRAY[100]}`,
      overflow: 'hidden',
    }}>
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: '12px 16px',
        borderBottom: `1px solid ${GRAY[100]}`,
      }}>
        <Text style={{ fontSize: 14, fontWeight: 700, color: GRAY[800] }}>알림</Text>
        {count > 0 && (
          <Button type="link" size="small" onClick={handleReadAll}
                  style={{ fontSize: 12, padding: 0 }}>
            모두 읽음
          </Button>
        )}
      </div>

      {notifications.length === 0 ? (
        <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="알림이 없습니다"
               style={{ padding: '24px 0' }} />
      ) : (
        <div style={{ maxHeight: 360, overflowY: 'auto' }}>
          {notifications.map((n: UserNotificationRow) => (
            <div
              key={n.notificationId}
              onClick={() => !n.isRead && handleRead(n.notificationId)}
              style={{
                padding: '10px 16px',
                cursor: n.isRead ? 'default' : 'pointer',
                background: n.isRead ? '#fff' : '#EBF3FF',
                borderBottom: `1px solid ${GRAY[100]}`,
              }}
            >
              <Space direction="vertical" size={2} style={{ width: '100%' }}>
                <Text style={{
                  fontSize: 13,
                  fontWeight: n.isRead ? 400 : 600,
                  color: GRAY[800],
                }}>
                  {n.title}
                </Text>
                <Text style={{ fontSize: 12, color: GRAY[500] }}>{n.content}</Text>
                <Text style={{ fontSize: 11, color: GRAY[400] }}>
                  {n.createdAt?.slice(0, 16)}
                </Text>
              </Space>
            </div>
          ))}
        </div>
      )}
    </div>
  );

  return (
    <Dropdown
      dropdownRender={() => overlay}
      placement="bottomRight"
      trigger={['click']}
    >
      <Badge count={count} size="small" offset={[-3, 3]}>
        <Button
          type="text"
          icon={<IconBell size={18} />}
          style={{
            color: GRAY[600],
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}
        />
      </Badge>
    </Dropdown>
  );
}
