import React, { useEffect, useState } from 'react';
import { Card, Tabs, Table, Tag, Button, Modal, Input, Space, message, Statistic, Row, Col, Switch, Form, InputNumber } from 'antd';
import {
  getInviteStats, getInviteRecords, getCashbackRecords,
  getInviteWithdrawals, approveInviteWithdrawal, rejectInviteWithdrawal, payInviteWithdrawal,
  getInviteConfig, updateInviteConfig,
} from '@/api/invite';
import dayjs from 'dayjs';

const InviteManage: React.FC = () => {
  const [stats, setStats] = useState<any>({});
  const [invitations, setInvitations] = useState<any[]>([]);
  const [invTotal, setInvTotal] = useState(0);
  const [invPage, setInvPage] = useState(1);
  const [invLoading, setInvLoading] = useState(false);

  const [cashbacks, setCashbacks] = useState<any[]>([]);
  const [cbTotal, setCbTotal] = useState(0);
  const [cbPage, setCbPage] = useState(1);
  const [cbLoading, setCbLoading] = useState(false);

  const [withdrawals, setWithdrawals] = useState<any[]>([]);
  const [wdTotal, setWdTotal] = useState(0);
  const [wdPage, setWdPage] = useState(1);
  const [wdLoading, setWdLoading] = useState(false);

  const [rejectModalOpen, setRejectModalOpen] = useState(false);
  const [currentWdId, setCurrentWdId] = useState<number | null>(null);
  const [rejectReason, setRejectReason] = useState('');

  const [config, setConfig] = useState<any>(null);
  const [configLoading, setConfigLoading] = useState(false);
  const [form] = Form.useForm();

  const fetchStats = async () => {
    try {
      const res = await getInviteStats();
      setStats(res.data || {});
    } catch {}
  };

  const fetchInvitations = async () => {
    setInvLoading(true);
    try {
      const res = await getInviteRecords({ page: invPage, pageSize: 10 });
      setInvitations(res.data?.list || []);
      setInvTotal(res.data?.total || 0);
    } finally {
      setInvLoading(false);
    }
  };

  const fetchCashbacks = async () => {
    setCbLoading(true);
    try {
      const res = await getCashbackRecords({ page: cbPage, pageSize: 10 });
      setCashbacks(res.data?.list || []);
      setCbTotal(res.data?.total || 0);
    } finally {
      setCbLoading(false);
    }
  };

  const fetchWithdrawals = async () => {
    setWdLoading(true);
    try {
      const res = await getInviteWithdrawals({ page: wdPage, pageSize: 10 });
      setWithdrawals(res.data?.list || []);
      setWdTotal(res.data?.total || 0);
    } finally {
      setWdLoading(false);
    }
  };

  const fetchConfig = async () => {
    setConfigLoading(true);
    try {
      const res = await getInviteConfig();
      setConfig(res.data);
      if (res.data?.config) {
        form.setFieldsValue(res.data.config);
      }
    } finally {
      setConfigLoading(false);
    }
  };

  useEffect(() => { fetchStats(); fetchConfig(); }, []);
  useEffect(() => { fetchInvitations(); }, [invPage]);
  useEffect(() => { fetchCashbacks(); }, [cbPage]);
  useEffect(() => { fetchWithdrawals(); }, [wdPage]);

  const handleApprove = async (wid: number) => {
    try { await approveInviteWithdrawal(wid); message.success('审核通过'); fetchWithdrawals(); fetchStats(); } catch {}
  };

  const handleReject = async () => {
    if (!rejectReason.trim()) { message.error('请输入拒绝原因'); return; }
    try {
      await rejectInviteWithdrawal(currentWdId!, rejectReason);
      message.success('已拒绝');
      setRejectModalOpen(false);
      setRejectReason('');
      fetchWithdrawals();
      fetchStats();
    } catch {}
  };

  const handlePay = async (wid: number) => {
    try { await payInviteWithdrawal(wid); message.success('已确认打款'); fetchWithdrawals(); fetchStats(); } catch {}
  };

  const handleToggle = async (enabled: boolean) => {
    try {
      await updateInviteConfig({ enabled });
      setConfig({ ...config, enabled });
      message.success(enabled ? '已启用' : '已停用');
    } catch {}
  };

  const handleSaveConfig = async () => {
    try {
      const values = await form.validateFields();
      await updateInviteConfig({ config: values });
      message.success('配置已保存');
      setConfig({ ...config, config: { ...config?.config, ...values } });
    } catch {}
  };

  const invColumns = [
    { title: 'ID', dataIndex: 'id', width: 60 },
    { title: '邀请人', render: (_: any, r: any) => r.inviter?.nickname || `用户${r.inviterId}` },
    { title: '被邀请人', render: (_: any, r: any) => r.invitee?.nickname || `用户${r.inviteeId}` },
    { title: '邀请码', dataIndex: 'inviteCode' },
    { title: '邀请时间', dataIndex: 'createdAt', render: (v: string) => v ? dayjs(v).format('YYYY-MM-DD HH:mm') : '-' },
  ];

  const cbColumns = [
    { title: 'ID', dataIndex: 'id', width: 60 },
    { title: '邀请人', render: (_: any, r: any) => r.inviter?.nickname || `用户${r.inviterId}` },
    { title: '被邀请人', render: (_: any, r: any) => r.invitee?.nickname || `用户${r.inviteeId}` },
    { title: '订单号', dataIndex: 'orderNo' },
    { title: '订单金额', dataIndex: 'orderAmount', render: (v: number) => `¥${v}` },
    { title: '第几单', dataIndex: 'orderIndex', render: (v: number) => `第${v}单` },
    { title: '返现比例', dataIndex: 'rate', render: (v: number) => `${(v * 100).toFixed(1)}%` },
    { title: '返现金额', dataIndex: 'amount', render: (v: number) => <Tag color="orange">¥{v}</Tag> },
    { title: '状态', dataIndex: 'status', render: (v: string) => {
      const map: any = { pending: '待结算', settled: '已到账', cancelled: '已取消' };
      const colors: any = { pending: 'default', settled: 'green', cancelled: 'red' };
      return <Tag color={colors[v]}>{map[v]}</Tag>;
    }},
    { title: '创建时间', dataIndex: 'createdAt', render: (v: string) => v ? dayjs(v).format('YYYY-MM-DD HH:mm') : '-' },
  ];

  const wdColumns = [
    { title: 'ID', dataIndex: 'id', width: 60 },
    { title: '用户', render: (_: any, r: any) => r.user?.nickname || `用户${r.userId}` },
    { title: '提现金额', dataIndex: 'amount', render: (v: number) => <Tag color="orange">¥{v}</Tag> },
    { title: '状态', dataIndex: 'status', render: (v: string) => {
      const map: any = { pending: '待审核', approved: '已通过', rejected: '已拒绝', paid: '已打款' };
      const colors: any = { pending: 'default', approved: 'blue', rejected: 'red', paid: 'green' };
      return <Tag color={colors[v]}>{map[v]}</Tag>;
    }},
    { title: '拒绝原因', dataIndex: 'rejectReason' },
    { title: '申请时间', dataIndex: 'createdAt', render: (v: string) => v ? dayjs(v).format('YYYY-MM-DD HH:mm') : '-' },
    {
      title: '操作',
      render: (_: any, r: any) => (
        <Space>
          {r.status === 'pending' && (
            <>
              <Button type="primary" size="small" onClick={() => handleApprove(r.id)}>通过</Button>
              <Button danger size="small" onClick={() => { setCurrentWdId(r.id); setRejectModalOpen(true); }}>拒绝</Button>
            </>
          )}
          {r.status === 'approved' && (
            <Button type="primary" size="small" onClick={() => handlePay(r.id)}>确认打款</Button>
          )}
        </Space>
      ),
    },
  ];

  const tabItems = [
    {
      key: 'overview',
      label: '数据概览',
      children: (
        <div>
          <Row gutter={16} style={{ marginBottom: 24 }}>
            <Col span={4}><Card><Statistic title="邀请总数" value={stats.totalInvitations || 0} /></Card></Col>
            <Col span={4}><Card><Statistic title="返现总笔数" value={stats.totalCashbacks || 0} /></Card></Col>
            <Col span={4}><Card><Statistic title="返现总金额" value={stats.totalCashbackAmount || 0} prefix="¥" precision={2} /></Card></Col>
            <Col span={4}><Card><Statistic title="提现申请数" value={stats.totalWithdrawals || 0} /></Card></Col>
            <Col span={4}><Card><Statistic title="待审核提现" value={stats.pendingWithdrawals || 0} valueStyle={{ color: '#faad14' }} /></Card></Col>
          </Row>
          <Card title={`邀请记录 (${invTotal})`} style={{ marginBottom: 16 }}>
            <Table rowKey="id" columns={invColumns} dataSource={invitations} loading={invLoading} size="small"
              pagination={{ current: invPage, total: invTotal, pageSize: 10, onChange: setInvPage }} />
          </Card>
          <Card title={`返现记录 (${cbTotal})`}>
            <Table rowKey="id" columns={cbColumns} dataSource={cashbacks} loading={cbLoading} size="small"
              pagination={{ current: cbPage, total: cbTotal, pageSize: 10, onChange: setCbPage }} />
          </Card>
        </div>
      ),
    },
    {
      key: 'withdrawals',
      label: `提现审核${stats.pendingWithdrawals ? ` (${stats.pendingWithdrawals})` : ''}`,
      children: (
        <Table rowKey="id" columns={wdColumns} dataSource={withdrawals} loading={wdLoading}
          pagination={{ current: wdPage, total: wdTotal, pageSize: 10, onChange: setWdPage }} />
      ),
    },
    {
      key: 'config',
      label: '活动配置',
      children: (
        <Card loading={configLoading}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
            <span style={{ fontSize: 16, fontWeight: 600 }}>邀请返现活动</span>
            <Switch checked={config?.enabled} onChange={handleToggle} checkedChildren="启用" unCheckedChildren="停用" />
          </div>
          <Form form={form} layout="vertical" style={{ maxWidth: 500 }}>
            <Form.Item label="首单返现比例" name="firstOrderRate" rules={[{ required: true }]} extra="好友首次下单，邀请人获得的返现比例">
              <InputNumber min={0.01} max={0.20} step={0.01} addonAfter="%" style={{ width: '100%' }}
                formatter={v => `${(Number(v) * 100).toFixed(1)}`} parser={v => Number(v?.replace('%', '')) / 100 as any} />
            </Form.Item>
            <Form.Item label="二单返现比例" name="secondOrderRate" rules={[{ required: true }]} extra="好友再次下单，邀请人获得的返现比例">
              <InputNumber min={0.001} max={0.05} step={0.001} addonAfter="%" style={{ width: '100%' }}
                formatter={v => `${(Number(v) * 100).toFixed(2)}`} parser={v => Number(v?.replace('%', '')) / 100 as any} />
            </Form.Item>
            <Form.Item label="最多返现订单数" name="maxOrderIndex" rules={[{ required: true }]} extra="好友最多前几单可以获得返现">
              <InputNumber min={1} max={10} step={1} addonAfter="单" style={{ width: '100%' }} />
            </Form.Item>
            <Form.Item label="最低返现金额" name="minCashback" rules={[{ required: true }]} extra="单笔返现最低金额">
              <InputNumber min={0.01} max={1} step={0.01} prefix="¥" style={{ width: '100%' }} />
            </Form.Item>
            <Form.Item label="最高返现金额" name="maxCashback" rules={[{ required: true }]} extra="单笔返现最高金额">
              <InputNumber min={10} max={500} step={10} prefix="¥" style={{ width: '100%' }} />
            </Form.Item>
            <Form.Item label="提现门槛" name="withdrawThreshold" rules={[{ required: true }]} extra="用户余额满多少元可以申请提现">
              <InputNumber min={1} max={100} step={1} prefix="¥" style={{ width: '100%' }} />
            </Form.Item>
            <Form.Item>
              <Button type="primary" onClick={handleSaveConfig}>保存配置</Button>
            </Form.Item>
          </Form>
        </Card>
      ),
    },
  ];

  return (
    <div>
      <h2 style={{ marginBottom: 16 }}>邀请返现管理</h2>
      <Card>
        <Tabs items={tabItems} />
      </Card>
      <Modal title="拒绝原因" open={rejectModalOpen} onOk={handleReject} onCancel={() => setRejectModalOpen(false)}>
        <Input.TextArea rows={3} value={rejectReason} onChange={e => setRejectReason(e.target.value)} placeholder="请输入拒绝原因" />
      </Modal>
    </div>
  );
};

export default InviteManage;