import {
  useState,
  useEffect,
  Card,
  Row,
  Col,
  Statistic,
  Button,
  Table,
  Tag,
  Space,
  DatePicker,
  Select,
  Tabs,
  Typography,
  Progress,
  ArrowUpOutlined,
  ArrowDownOutlined,
  DollarOutlined,
  CreditCardOutlined,
  BarChartOutlined,
  TransactionOutlined,
  ReloadOutlined,
  DownloadOutlined,
  useNavigate,
  Line,
  Column,
  Pie,
  Title,
  Text,
  RangePicker,
  Option,
  message,
  FC,
} from '@/imports';
import type { ColumnsType } from 'antd/es/table';
import moment from 'moment';
import { financeDataSource } from '@/services/financeDataSource';
import type { Transaction as FinanceTransaction } from '@/services/financeDataSource';

interface FinanceStats {
  totalIncome: number;
  totalExpense: number;
  netProfit: number;
  pendingAmount: number;
  monthlyIncome: number;
  monthlyExpense: number;
  monthlyProfit: number;
  incomeGrowth: number;
  expenseGrowth: number;
  profitGrowth: number;
}

const MOCK_STATS: FinanceStats = {
  totalIncome: 1250000,
  totalExpense: 850000,
  netProfit: 400000,
  pendingAmount: 15000,
  monthlyIncome: 125000,
  monthlyExpense: 85000,
  monthlyProfit: 40000,
  incomeGrowth: 12.5,
  expenseGrowth: 8.3,
  profitGrowth: 18.2,
};

const TREND_DATA = [
  { date: '2026-03-12', income: 45000, expense: 28000, profit: 17000 },
  { date: '2026-03-13', income: 52000, expense: 32000, profit: 20000 },
  { date: '2026-03-14', income: 48000, expense: 30000, profit: 18000 },
  { date: '2026-03-15', income: 61000, expense: 38000, profit: 23000 },
  { date: '2026-03-16', income: 55000, expense: 35000, profit: 20000 },
  { date: '2026-03-17', income: 67000, expense: 42000, profit: 25000 },
  { date: '2026-03-18', income: 72000, expense: 45000, profit: 27000 },
];

const Finance: FC = () => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [transactions, setTransactions] = useState<FinanceTransaction[]>([]);
  const [stats, setStats] = useState<FinanceStats>(MOCK_STATS);
  const [activeTab, setActiveTab] = useState('overview');
  const [timeRange, setTimeRange] = useState<any>(null);
  const [platform, setPlatform] = useState<string>('all');
  const [incomeSources, setIncomeSources] = useState<any[]>([]);
  const [costStructure, setCostStructure] = useState<any[]>([]);

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

  const loadData = async () => {
    setLoading(true);
    try {
      // 加载交易记录
      const transactionData = await financeDataSource.fetchTransactions({
        startDate: timeRange?.[0]?.format('YYYY-MM-DD'),
        endDate: timeRange?.[1]?.format('YYYY-MM-DD'),
      });
      setTransactions(transactionData);

      // 计算统计数据
      calculateStats(transactionData);

      // 准备财务分析数据
      prepareAnalysisData(transactionData);
    } catch (error) {
      console.error('Failed to load finance data:', error);
      message.error('加载财务数据失败');
    } finally {
      setLoading(false);
    }
  };

  const calculateStats = (transactionData: FinanceTransaction[]) => {
    const totalIncome = transactionData
      .filter(t => t.type === 'income')
      .reduce((sum, t) => sum + t.amount, 0);
    const totalExpense = transactionData
      .filter(t => ['expense', 'fee', 'refund'].includes(t.type))
      .reduce((sum, t) => sum + t.amount, 0);
    const netProfit = totalIncome - totalExpense;
    const pendingAmount = transactionData
      .filter(t => t.status === 'pending')
      .reduce((sum, t) => sum + t.amount, 0);

    setStats({
      ...MOCK_STATS,
      totalIncome,
      totalExpense,
      netProfit,
      pendingAmount,
    });
  };

  const prepareAnalysisData = (transactionData: FinanceTransaction[]) => {
    // 收入来源分析
    const incomeByCategory = transactionData
      .filter(t => t.type === 'income')
      .reduce((acc, t) => {
        acc[t.category] = (acc[t.category] || 0) + t.amount;
        return acc;
      }, {} as Record<string, number>);

    const incomeSourceData = Object.entries(incomeByCategory).map(([category, value]) => ({
      category,
      value,
    }));
    setIncomeSources(incomeSourceData);

    // 成本结构分析
    const expenseByCategory = transactionData
      .filter(t => ['expense', 'fee'].includes(t.type))
      .reduce((acc, t) => {
        acc[t.category] = (acc[t.category] || 0) + t.amount;
        return acc;
      }, {} as Record<string, number>);

    const costStructureData = Object.entries(expenseByCategory).map(([category, value]) => ({
      category,
      value,
    }));
    setCostStructure(costStructureData);
  };

  const handleTimeRangeChange = (dates: any) => {
    setTimeRange(dates);
  };

  const handlePlatformChange = (value: string) => {
    setPlatform(value);
  };

  const handleRefresh = () => {
    loadData();
  };

  const handleExport = async () => {
    try {
      message.success('导出成功');
    } catch (error) {
      console.error('Failed to export:', error);
      message.error('导出失败');
    }
  };

  const typeColors: Record<string, string> = {
    income: 'success',
    expense: 'error',
    refund: 'warning',
    fee: 'processing',
  };

  const typeTexts: Record<string, string> = {
    income: '收入',
    expense: '支出',
    refund: '退款',
    fee: '费用',
  };

  const statusColors: Record<string, string> = {
    pending: 'warning',
    completed: 'success',
    failed: 'error',
  };

  const columns: ColumnsType<FinanceTransaction> = [
    {
      title: '交易号',
      dataIndex: 'id',
      key: 'id',
      render: (text) => <Text strong>{text}</Text>,
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      render: (type) => <Tag color={typeColors[type]}>{typeTexts[type]}</Tag>,
    },
    {
      title: '金额',
      dataIndex: 'amount',
      key: 'amount',
      render: (amount, record) => (
        <Text style={{ color: record.type === 'income' ? '#52c41a' : '#ff4d4f' }}>
          {record.type === 'income' ? '+' : '-'}{$amount.toFixed(2)}
        </Text>
      ),
    },
    {
      title: '类别',
      dataIndex: 'category',
      key: 'category',
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      ellipsis: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => <Tag color={statusColors[status]}>{status}</Tag>,
    },
    {
      title: '时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
    },
  ];

  const trendConfig = {
    data: TREND_DATA.flatMap(item => [
      { date: item.date, value: item.income, type: '收入' },
      { date: item.date, value: item.expense, type: '支出' },
      { date: item.date, value: item.profit, type: '利润' },
    ]),
    xField: 'date',
    yField: 'value',
    seriesField: 'type',
    smooth: true,
    legend: { position: 'top' as const },
  };

  const categoryConfig = {
    data: [
      { category: '销售收入', value: 850000 },
      { category: '采购成本', value: 450000 },
      { category: '物流费用', value: 120000 },
      { category: '平台费用', value: 95000 },
      { category: '广告费用', value: 85000 },
      { category: '其他', value: 100000 },
    ],
    xField: 'value',
    yField: 'category',
    seriesField: 'category',
    legend: false,
  };

  const incomeSourceConfig = {
    data: incomeSources,
    angleField: 'value',
    colorField: 'category',
    radius: 0.8,
    label: {
      type: 'outer',
      content: '{category}: {value}',
    },
    legend: { position: 'bottom' as const },
  };

  const costStructureConfig = {
    data: costStructure,
    angleField: 'value',
    colorField: 'category',
    radius: 0.8,
    label: {
      type: 'outer',
      content: '{category}: {value}',
    },
    legend: { position: 'bottom' as const },
  };

  const tabItems = [
    { key: 'overview', label: '财务概览' },
    { key: 'transactions', label: '交易记录' },
    { key: 'analysis', label: '财务分析' },
  ];

  return (
    <div className="finance">
      <Row justify="space-between" align="middle" style={{ marginBottom: 24 }}>
        <Col>
          <Title level={4}>财务管理</Title>
          <Text type="secondary">实时监控财务数据和资金流向</Text>
        </Col>
        <Col>
          <Space>
            <RangePicker onChange={handleTimeRangeChange} />
            <Select value={platform} style={{ width: 120 }} onChange={handlePlatformChange}>
              <Option value="all">全部平台</Option>
              <Option value="amazon">Amazon</Option>
              <Option value="ebay">eBay</Option>
              <Option value="shopify">Shopify</Option>
            </Select>
            <Button icon={<ReloadOutlined />} onClick={handleRefresh} loading={loading}>
              刷新
            </Button>
            <Button icon={<DownloadOutlined />} onClick={handleExport}>
              导出
            </Button>
          </Space>
        </Col>
      </Row>

      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col xs={24} sm={12} lg={6}>
          <Card>
            <Statistic
              title="总收入"
              value={stats.totalIncome}
              precision={2}
              prefix={<DollarOutlined />}
              valueStyle={{ color: '#3f8600' }}
              suffix={
                <Text style={{ fontSize: 14, marginLeft: 8 }}>
                  <ArrowUpOutlined /> {stats.incomeGrowth}%
                </Text>
              }
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card>
            <Statistic
              title="总支出"
              value={stats.totalExpense}
              precision={2}
              prefix={<CreditCardOutlined />}
              valueStyle={{ color: '#cf1322' }}
              suffix={
                <Text style={{ fontSize: 14, marginLeft: 8 }}>
                  <ArrowUpOutlined /> {stats.expenseGrowth}%
                </Text>
              }
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card>
            <Statistic
              title="净利润"
              value={stats.netProfit}
              precision={2}
              prefix={<BarChartOutlined />}
              valueStyle={{ color: '#3f8600' }}
              suffix={
                <Text style={{ fontSize: 14, marginLeft: 8 }}>
                  <ArrowUpOutlined /> {stats.profitGrowth}%
                </Text>
              }
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card>
            <Statistic
              title="待结算"
              value={stats.pendingAmount}
              precision={2}
              prefix={<TransactionOutlined />}
              valueStyle={{ color: '#faad14' }}
            />
            <Progress percent={60} size="small" showInfo={false} style={{ marginTop: 8 }} />
          </Card>
        </Col>
      </Row>

      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col xs={24} sm={8}>
          <Card size="small">
            <Statistic
              title="本月收入"
              value={stats.monthlyIncome}
              precision={2}
              prefix={<ArrowUpOutlined style={{ color: '#52c41a' }} />}
              valueStyle={{ fontSize: 18, color: '#52c41a' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={8}>
          <Card size="small">
            <Statistic
              title="本月支出"
              value={stats.monthlyExpense}
              precision={2}
              prefix={<ArrowDownOutlined style={{ color: '#ff4d4f' }} />}
              valueStyle={{ fontSize: 18, color: '#ff4d4f' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={8}>
          <Card size="small">
            <Statistic
              title="本月利润"
              value={stats.monthlyProfit}
              precision={2}
              prefix={<BarChartOutlined style={{ color: '#1890ff' }} />}
              valueStyle={{ fontSize: 18, color: '#1890ff' }}
            />
          </Card>
        </Col>
      </Row>

      <Tabs activeKey={activeTab} onChange={setActiveTab} items={tabItems} style={{ marginBottom: 24 }} />

      {activeTab === 'overview' && (
        <Row gutter={16}>
          <Col xs={24} lg={16}>
            <Card title="收支趋势">
              <Line {...trendConfig} height={300} />
            </Card>
          </Col>
          <Col xs={24} lg={8}>
            <Card title="支出分类">
              <Column {...categoryConfig} height={300} />
            </Card>
          </Col>
        </Row>
      )}

      {activeTab === 'transactions' && (
        <Card title="最近交易">
          <Table
            columns={columns}
            dataSource={transactions}
            rowKey="id"
            pagination={{ pageSize: 10 }}
            loading={loading}
          />
        </Card>
      )}

      {activeTab === 'analysis' && (
        <Row gutter={16}>
          <Col span={12}>
            <Card title="收入来源分析">
              {incomeSources.length > 0 ? (
                <Pie {...incomeSourceConfig} height={300} />
              ) : (
                <div style={{ padding: '40px 0', textAlign: 'center' }}>
                  <Text type="secondary">暂无数据</Text>
                </div>
              )}
            </Card>
          </Col>
          <Col span={12}>
            <Card title="成本结构分析">
              {costStructure.length > 0 ? (
                <Pie {...costStructureConfig} height={300} />
              ) : (
                <div style={{ padding: '40px 0', textAlign: 'center' }}>
                  <Text type="secondary">暂无数据</Text>
                </div>
              )}
            </Card>
          </Col>
        </Row>
      )}

      <Row gutter={16} style={{ marginTop: 24 }}>
        <Col span={8}>
          <Button type="primary" block onClick={() => navigate('/dashboard/finance/transactions')}>
            查看交易记录
          </Button>
        </Col>
        <Col span={8}>
          <Button type="primary" block onClick={() => navigate('/dashboard/finance/reconciliation')}>
            查看对账记录
          </Button>
        </Col>
        <Col span={8}>
          <Button type="primary" block onClick={() => navigate('/dashboard/reports/profit')}>
            查看利润报表
          </Button>
        </Col>
      </Row>
    </div>
  );
};

export default Finance;