import React, { useEffect, useState } from 'react';
import { Card, Row, Col, Statistic, Table, Tag } from 'antd';
import { WalletOutlined, ArrowUpOutlined, ArrowDownOutlined, DollarOutlined, TeamOutlined } from '@ant-design/icons';
import { getFinancialOverview, getPlatformTransactions } from '@/api/finance';
import type { ColumnsType } from 'antd/es/table';

interface FinancialOverview {
  platformBalance: number;
  totalUserBalance: number;
  totalMerchantBalance: number;
  todayIncome: number;
  todayExpense: number;
  monthIncome: number;
  monthExpense: number;
  pendingWithdrawals: number;
  pendingSettlements: number;
}

interface Transaction {
  id: number;
  type: string;
  amount: number;
  balance: number;
  description: string;
  createdAt: string;
}

const FinanceDashboard: React.FC = () => {
  const [overview, setOverview] = useState<FinancialOverview | null>(null);
  const [recentTransactions, setRecentTransactions] = useState<Transaction[]>([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    fetchOverview();
    fetchRecentTransactions();
  }, []);

  const fetchOverview = async () => {
    try {
      const res = await getFinancialOverview({});
      setOverview(res.data);
    } catch (error) {
      console.error('获取财务总览失败', error);
    }
  };

  const fetchRecentTransactions = async () => {
    setLoading(true);
    try {
      const res = await getPlatformTransactions({ page: 1, pageSize: 10 });
      setRecentTransactions(res.data.items);
    } catch (error) {
      console.error('获取最近交易失败', error);
    } finally {
      setLoading(false);
    }
  };

  const columns: ColumnsType<Transaction> = [
    {
      title: '交易时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 180,
    },
    {
      title: '交易类型',
      dataIndex: 'type',
      key: 'type',
      width: 120,
      render: (type: string) => {
        const typeMap: Record<string, { text: string; color: string }> = {
          income: { text: '收入', color: 'green' },
          expense: { text: '支出', color: 'red' },
        };
        const config = typeMap[type] || { text: type, color: 'default' };
        return <Tag color={config.color}>{config.text}</Tag>;
      },
    },
    {
      title: '金额',
      dataIndex: 'amount',
      key: 'amount',
      width: 120,
      render: (amount: number, record: Transaction) => (
        <span style={{ color: record.type === 'income' ? '#52c41a' : '#ff4d4f' }}>
          {record.type === 'income' ? '+' : '-'}¥{amount.toFixed(2)}
        </span>
      ),
    },
    {
      title: '余额',
      dataIndex: 'balance',
      key: 'balance',
      width: 120,
      render: (balance: number) => `¥${balance.toFixed(2)}`,
    },
    {
      title: '说明',
      dataIndex: 'description',
      key: 'description',
    },
  ];

  return (
    <div>
      <h2 style={{ marginBottom: 24 }}>财务总览</h2>

      {overview && (
        <>
          {/* 平台总账户余额 - 突出显示 */}
          <Card style={{ marginBottom: 24, background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)' }}>
            <Statistic
              title={<span style={{ color: '#fff', fontSize: 16 }}>平台总账户余额</span>}
              value={Number(overview.platformBalance || 0) + Number(overview.totalMerchantBalance || 0) + Number(overview.totalUserBalance || 0)}
              prefix={<WalletOutlined style={{ color: '#fff' }} />}
              suffix={<span style={{ color: '#fff' }}>元</span>}
              precision={2}
              valueStyle={{ color: '#fff', fontSize: 36, fontWeight: 'bold' }}
            />
            <div style={{ color: 'rgba(255,255,255,0.8)', fontSize: 12, marginTop: 8 }}>
              平台内所有未提现的资金总额（包含平台钱包、商家账户、用户账户）
            </div>
          </Card>

          <Row gutter={24} style={{ marginBottom: 24 }}>
            <Col span={6}>
              <Card>
                <Statistic
                  title="平台账户余额"
                  value={overview.platformBalance}
                  precision={2}
                  prefix={<WalletOutlined />}
                  suffix="元"
                  valueStyle={{ color: '#1890ff' }}
                />
              </Card>
            </Col>
            <Col span={6}>
              <Card>
                <Statistic
                  title="用户总余额"
                  value={overview.totalUserBalance}
                  precision={2}
                  prefix={<TeamOutlined />}
                  suffix="元"
                  valueStyle={{ color: '#52c41a' }}
                />
              </Card>
            </Col>
            <Col span={6}>
              <Card>
                <Statistic
                  title="商家总余额"
                  value={overview.totalMerchantBalance}
                  precision={2}
                  prefix={<DollarOutlined />}
                  suffix="元"
                  valueStyle={{ color: '#faad14' }}
                />
              </Card>
            </Col>
            <Col span={6}>
              <Card>
                <Statistic
                  title="待处理提现"
                  value={overview.pendingWithdrawals}
                  precision={2}
                  suffix="元"
                  valueStyle={{ color: '#ff4d4f' }}
                />
              </Card>
            </Col>
          </Row>

          <Row gutter={24} style={{ marginBottom: 24 }}>
            <Col span={6}>
              <Card>
                <Statistic
                  title="今日收入"
                  value={overview.todayIncome}
                  precision={2}
                  prefix={<ArrowUpOutlined />}
                  suffix="元"
                  valueStyle={{ color: '#52c41a' }}
                />
              </Card>
            </Col>
            <Col span={6}>
              <Card>
                <Statistic
                  title="今日支出"
                  value={overview.todayExpense}
                  precision={2}
                  prefix={<ArrowDownOutlined />}
                  suffix="元"
                  valueStyle={{ color: '#ff4d4f' }}
                />
              </Card>
            </Col>
            <Col span={6}>
              <Card>
                <Statistic
                  title="本月收入"
                  value={overview.monthIncome}
                  precision={2}
                  prefix={<ArrowUpOutlined />}
                  suffix="元"
                  valueStyle={{ color: '#52c41a' }}
                />
              </Card>
            </Col>
            <Col span={6}>
              <Card>
                <Statistic
                  title="本月支出"
                  value={overview.monthExpense}
                  precision={2}
                  prefix={<ArrowDownOutlined />}
                  suffix="元"
                  valueStyle={{ color: '#ff4d4f' }}
                />
              </Card>
            </Col>
          </Row>
        </>
      )}

      <Card title="最近交易">
        <Table
          columns={columns}
          dataSource={recentTransactions}
          rowKey="id"
          loading={loading}
          pagination={false}
        />
      </Card>
    </div>
  );
};

export default FinanceDashboard;
