import { useEffect, useState, useCallback } from 'react';
import {
  Card, Button, Row, Col, Statistic, Table, Typography, Space,
  Input, InputNumber, Form, Drawer, Spin, Grid, App, Empty,
} from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { PlusOutlined, GiftOutlined, TeamOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import { api } from '@/lib/api';
import InviteCodeCard from '@/components/social/InviteCodeCard';

interface InviteCode {
  id: string;
  code: string;
  maxUses: number;
  usedCount: number;
  expiresAt: string | null;
  isActive: boolean;
  note: string | null;
  createdAt: string;
  _count?: { referrals: number };
}

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

interface ReferralStats {
  totalReferrals: number;
  thisMonth: number;
}

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

  const [codes, setCodes] = useState<InviteCode[]>([]);
  const [referrals, setReferrals] = useState<ReferralRow[]>([]);
  const [stats, setStats] = useState<ReferralStats | null>(null);
  const [loading, setLoading] = useState(true);
  const [createOpen, setCreateOpen] = useState(false);
  const [creating, setCreating] = useState(false);
  const [deactivatingId, setDeactivatingId] = useState<string | null>(null);
  const [refPage, setRefPage] = useState(1);
  const [refTotal, setRefTotal] = useState(0);

  const [form] = Form.useForm();

  const loadData = useCallback(async () => {
    setLoading(true);
    try {
      const [codesRes, referralsRes, statsRes] = await Promise.all([
        api.get('/social/referrals/codes', { params: { limit: 50 } }),
        api.get('/social/referrals/my-referrals', { params: { page: refPage, limit: 10 } }),
        api.get('/social/referrals/stats'),
      ]);
      setCodes(codesRes.data.codes);
      setReferrals(referralsRes.data.referrals);
      setRefTotal(referralsRes.data.pagination.total);
      setStats(statsRes.data);
    } catch {
      message.error('Failed to load referral data');
    } finally {
      setLoading(false);
    }
  }, [refPage]); // eslint-disable-line react-hooks/exhaustive-deps

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

  const handleCreate = async (values: { maxUses?: number; expiresInDays?: number; note?: string }) => {
    setCreating(true);
    try {
      await api.post('/social/referrals/codes', values);
      message.success('Invite code created');
      setCreateOpen(false);
      form.resetFields();
      loadData();
    } catch {
      message.error('Failed to create invite code');
    } finally {
      setCreating(false);
    }
  };

  const handleDeactivate = async (id: string) => {
    setDeactivatingId(id);
    try {
      await api.delete(`/social/referrals/codes/${id}`);
      message.success('Code deactivated');
      loadData();
    } catch {
      message.error('Failed to deactivate code');
    } finally {
      setDeactivatingId(null);
    }
  };

  const referralColumns: ColumnsType<ReferralRow> = [
    {
      title: 'Person',
      key: 'person',
      render: (_: unknown, r: ReferralRow) => r.referredUser.name || r.referredUser.email,
    },
    {
      title: 'Date',
      dataIndex: 'completedAt',
      key: 'date',
      render: (v: string) => dayjs(v).format('MMM D, YYYY'),
    },
  ];

  if (loading) {
    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%' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 8 }}>
          <Typography.Title level={4} style={{ margin: 0 }}>My Referrals</Typography.Title>
          <Button type="primary" icon={<PlusOutlined />} onClick={() => setCreateOpen(true)}>
            Create Invite Code
          </Button>
        </div>

        {/* Stats */}
        <Row gutter={[16, 16]}>
          <Col xs={12} sm={8}>
            <Card size="small">
              <Statistic
                title="Total Referrals"
                value={stats?.totalReferrals ?? 0}
                prefix={<TeamOutlined />}
              />
            </Card>
          </Col>
          <Col xs={12} sm={8}>
            <Card size="small">
              <Statistic
                title="This Month"
                value={stats?.thisMonth ?? 0}
                prefix={<GiftOutlined />}
              />
            </Card>
          </Col>
          <Col xs={12} sm={8}>
            <Card size="small">
              <Statistic title="Active Codes" value={codes.filter((c) => c.isActive).length} />
            </Card>
          </Col>
        </Row>

        {/* Invite Codes */}
        <Card title="My Invite Codes" size="small">
          {codes.length === 0 ? (
            <Empty description="No invite codes yet. Create one to start referring people!" />
          ) : (
            <Space direction="vertical" style={{ width: '100%' }} size="small">
              {codes.map((code) => (
                <InviteCodeCard
                  key={code.id}
                  code={code}
                  onDeactivate={handleDeactivate}
                  deactivating={deactivatingId === code.id}
                />
              ))}
            </Space>
          )}
        </Card>

        {/* My Referrals */}
        <Card title="People I Referred" size="small">
          <Table
            dataSource={referrals}
            columns={referralColumns}
            scroll={{ x: 'max-content' }}
            rowKey="id"
            size="small"
            pagination={{
              current: refPage,
              total: refTotal,
              pageSize: 10,
              onChange: setRefPage,
              showSizeChanger: false,
            }}
            locale={{ emptyText: 'No referrals yet' }}
          />
        </Card>
      </Space>

      {/* Create Code Drawer */}
      <Drawer
        title="Create Invite Code"
        open={createOpen}
        onClose={() => { setCreateOpen(false); form.resetFields(); }}
        placement="right"
        width={420}
        mask={false}
        rootStyle={{ position: 'absolute', top: 64, height: 'calc(100vh - 64px)' }}
        destroyOnHidden
        extra={
          <Button type="primary" loading={creating} onClick={() => form.submit()}>
            Create
          </Button>
        }
      >
        <Form form={form} layout="vertical" onFinish={handleCreate}>
          <Form.Item name="maxUses" label="Max Uses (0 = unlimited)">
            <InputNumber min={0} style={{ width: '100%' }} placeholder="0" />
          </Form.Item>
          <Form.Item name="expiresInDays" label="Expires In (days)">
            <InputNumber min={1} max={365} style={{ width: '100%' }} placeholder="No expiry" />
          </Form.Item>
          <Form.Item name="note" label="Note">
            <Input.TextArea maxLength={200} rows={2} placeholder="Optional note for your reference" />
          </Form.Item>
        </Form>
      </Drawer>
    </div>
  );
}
