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 { getAccountDisplayName } from '@/utils/accountNameMap';
import type { ColumnsType } from 'antd/es/table';

interface FinancialOverview {
  systemTotalAmount: number;
  totalUserPaid: number;
  totalRefund: number;
  totalWithdrawn: number;
  platformBalance: number;
  platformTotalIncome: number;
  platformTotalExpense: number;
  totalUserBalance: number;
  totalMerchantBalance: number;
  totalMerchantPendingSettlement: number;
  userCount: number;
  merchantCount: number;
  todayIncome: number;
  todayExpense: number;
}

interface Transaction {
  id: number;
  transaction_no: string;
  direction: 'income' | 'expense';
  amount: number;
  balance_after: number;
  transaction_type: string;
  remark: string;
  created_at: 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.list || res.data.items || []);
    } catch (error) {
      console.error('获取最近交易失败', error);
    } finally {
      setLoading(false);
    }
  };

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

  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.systemTotalAmount || 0)}
              prefix={<WalletOutlined style={{ color: '#fff' }} />}
              suffix={<span style={{ color: '#fff' }}>元 ({getAccountDisplayName('SYSTEM_MAIN')})</span>}
              precision={2}
              valueStyle={{ color: '#fff', fontSize: 36, fontWeight: 'bold' }}
            />
           {/* <div style={{ color: 'rgba(255,255,255,0.9)', fontSize: 13, marginTop: 8, fontWeight: 500 }}>
              商家账户余额（¥{Number(overview.totalMerchantBalance || 0).toFixed(2)}）+ 用户账户余额（¥{Number(overview.totalUserBalance || 0).toFixed(2)}）+ 平台净收益（¥{Number(overview.platformBalance || 0).toFixed(2)}）
            </div>
             */}
            <div style={{ color: 'rgba(255,255,255,0.7)', fontSize: 11, marginTop: 6 }}>
              系统总账户 balance = 用户实付（¥{Number(overview.totalUserPaid || 0).toFixed(2)}）- 退款（¥{Number(overview.totalRefund || 0).toFixed(2)}）- 提现（¥{Number(overview.totalWithdrawn || 0).toFixed(2)}）= ¥{(Number(overview.totalUserPaid || 0) - Number(overview.totalRefund || 0) - Number(overview.totalWithdrawn || 0)).toFixed(2)}
            </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' }}
                />
                <div style={{ fontSize: 12, color: '#999', marginTop: 8 }}>
                  服务费收入 - 邀请返现
                </div>
              </Card>
            </Col>
            <Col span={6}>
              <Card>
                <Statistic
                  title="用户总余额"
                  value={overview.totalUserBalance}
                  precision={2}
                  prefix={<TeamOutlined />}
                  suffix="元"
                  valueStyle={{ color: '#52c41a' }}
                />
                <div style={{ fontSize: 12, color: '#999', marginTop: 8 }}>
                  {overview.userCount} 个用户账户
                </div>
              </Card>
            </Col>
            <Col span={6}>
              <Card>
                <Statistic
                  title="商家总余额"
                  value={overview.totalMerchantBalance}
                  precision={2}
                  prefix={<DollarOutlined />}
                  suffix="元"
                  valueStyle={{ color: '#faad14' }}
                />
                <div style={{ fontSize: 12, color: '#999', marginTop: 8 }}>
                  {overview.merchantCount} 个商家账户
                </div>
              </Card>
            </Col>
            <Col span={6}>
              <Card>
                <Statistic
                  title="商家待结算金额"
                  value={overview.totalMerchantPendingSettlement}
                  precision={2}
                  prefix={<DollarOutlined />}
                  suffix="元"
                  valueStyle={{ color: '#ff9800' }}
                />
                <div style={{ fontSize: 12, color: '#999', marginTop: 8 }}>
                  待结算订单金额
                </div>
              </Card>
            </Col>
          </Row>

          <Row gutter={24} style={{ marginBottom: 24 }}>
            <Col span={8}>
              <Card>
                <Statistic
                  title="今日收入"
                  value={overview.todayIncome}
                  precision={2}
                  prefix={<ArrowUpOutlined />}
                  suffix="元"
                  valueStyle={{ color: '#52c41a' }}
                />
              </Card>
            </Col>
            <Col span={8}>
              <Card>
                <Statistic
                  title="今日支出"
                  value={overview.todayExpense}
                  precision={2}
                  prefix={<ArrowDownOutlined />}
                  suffix="元"
                  valueStyle={{ color: '#ff4d4f' }}
                />
              </Card>
            </Col>
            <Col span={8}>
              <Card>
                <Statistic
                  title="今日净收益"
                  value={Number(overview.todayIncome || 0) - Number(overview.todayExpense || 0)}
                  precision={2}
                  suffix="元"
                  valueStyle={{
                    color: (Number(overview.todayIncome || 0) - Number(overview.todayExpense || 0)) >= 0 ? '#52c41a' : '#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;
