import { useEffect, useState, useCallback } from 'react';
import { Card, Table, Typography, Space, Spin, Row, Col, Grid, App } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { TrophyOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import { api } from '@/lib/api';

interface AdminReferralRow {
  id: number;
  completedAt: string;
  referralSource: string | null;
  referrer: { id: string; name: string | null; email: string };
  referredUser: { id: string; name: string | null; email: string };
}

interface LeaderboardEntry {
  rank: number;
  userId: string;
  name: string | null;
  email: string;
  referralCount: number;
}

export default function ReferralAdminPage() {
  const { message } = App.useApp();
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;

  const [referrals, setReferrals] = useState<AdminReferralRow[]>([]);
  const [leaderboard, setLeaderboard] = useState<LeaderboardEntry[]>([]);
  const [loading, setLoading] = useState(true);
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(0);

  const loadData = useCallback(async () => {
    setLoading(true);
    try {
      const [refRes, lbRes] = await Promise.all([
        api.get('/social/referrals/admin/all', { params: { page, limit: 20 } }),
        api.get('/social/referrals/admin/leaderboard', { params: { limit: 10 } }),
      ]);
      setReferrals(refRes.data.referrals);
      setTotal(refRes.data.pagination.total);
      setLeaderboard(lbRes.data.leaderboard);
    } catch {
      message.error('Failed to load referral data');
    } finally {
      setLoading(false);
    }
  }, [page]); // eslint-disable-line react-hooks/exhaustive-deps

  useEffect(() => { loadData(); }, [loadData]);

  const referralColumns: ColumnsType<AdminReferralRow> = [
    {
      title: 'Referrer',
      key: 'referrer',
      render: (_: unknown, r: AdminReferralRow) => r.referrer.name || r.referrer.email,
    },
    {
      title: 'Referred User',
      key: 'referred',
      render: (_: unknown, r: AdminReferralRow) => r.referredUser.name || r.referredUser.email,
    },
    {
      title: 'Source',
      dataIndex: 'referralSource',
      key: 'source',
      render: (v: string | null) => v || '-',
    },
    {
      title: 'Date',
      dataIndex: 'completedAt',
      key: 'date',
      render: (v: string) => dayjs(v).format('MMM D, YYYY'),
      responsive: ['md'] as any,
    },
  ];

  const leaderboardColumns: ColumnsType<LeaderboardEntry> = [
    {
      title: '#',
      dataIndex: 'rank',
      key: 'rank',
      width: 50,
    },
    {
      title: 'Name',
      key: 'name',
      render: (_: unknown, r: LeaderboardEntry) => r.name || r.email,
    },
    {
      title: 'Referrals',
      dataIndex: 'referralCount',
      key: 'count',
      width: 100,
    },
  ];

  if (loading && page === 1) {
    return <div style={{ textAlign: 'center', padding: 48 }}><Spin size="large" /></div>;
  }

  return (
    <div style={{ padding: isMobile ? 16 : 24 }}>
      <Space direction="vertical" size="large" style={{ width: '100%' }}>
        <Typography.Title level={4} style={{ margin: 0 }}>Referral Management</Typography.Title>

        <Row gutter={[24, 24]}>
          <Col xs={24} lg={16}>
            <Card title={`All Referrals (${total})`} size="small">
              <Table
                dataSource={referrals}
                columns={referralColumns}
                scroll={{ x: 'max-content' }}
                rowKey="id"
                size="small"
                loading={loading}
                pagination={{
                  current: page,
                  total,
                  pageSize: 20,
                  onChange: setPage,
                  showSizeChanger: false,
                }}
                locale={{ emptyText: 'No referrals yet' }}
              />
            </Card>
          </Col>
          <Col xs={24} lg={8}>
            <Card
              title={<span><TrophyOutlined style={{ marginRight: 8 }} />Top Referrers</span>}
              size="small"
            >
              <Table
                dataSource={leaderboard}
                columns={leaderboardColumns}
                scroll={{ x: 'max-content' }}
                rowKey="userId"
                size="small"
                pagination={false}
                locale={{ emptyText: 'No referrals yet' }}
              />
            </Card>
          </Col>
        </Row>
      </Space>
    </div>
  );
}
