import React, { useState, useEffect } from 'react';
import { Card, Row, Col, Select, DatePicker, Button, Table } from 'antd';
import { BarChart, Bar, LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer, PieChart, Pie, Cell } from 'recharts';
import { DownloadOutlined, RefreshOutlined } from '@ant-design/icons';
import { reportsDataSource, ProfitReport as ProfitReportData } from '@/services/reportsDataSource';

const { Option } = Select;
const { RangePicker } = DatePicker;

interface ProfitData {
  date: string;
  revenue: number;
  cost: number;
  profit: number;
  margin: number;
}

interface ProductProfit {
  id: string;
  name: string;
  revenue: number;
  cost: number;
  profit: number;
  margin: number;
  quantity: number;
}

interface CategoryProfit {
  name: string;
  value: number;
}

const ProfitReport: React.FC = () => {
  const [profitData, setProfitData] = useState<ProfitData[]>([]);
  const [productProfits, setProductProfits] = useState<ProductProfit[]>([]);
  const [categoryProfits, setCategoryProfits] = useState<CategoryProfit[]>([]);
  const [loading, setLoading] = useState(false);
  const [timeRange, setTimeRange] = useState('month');
  const [dateRange, setDateRange] = useState<any>(null);
  const [selectedCategory, setSelectedCategory] = useState('all');

  useEffect(() => {
    fetchProfitData();
  }, [timeRange, dateRange, selectedCategory]);

  const fetchProfitData = async () => {
    setLoading(true);
    // 模拟API调用
    setTimeout(() => {
      // 模拟利润数据
      const mockProfitData: ProfitData[] = Array.from({ length: 12 }, (_, i) => {
        const month = i + 1;
        const revenue = Math.random() * 100000 + 50000;
        const cost = revenue * (0.6 + Math.random() * 0.2);
        const profit = revenue - cost;
        const margin = (profit / revenue) * 100;
        return {
          date: `2026-${String(month).padStart(2, '0')}`,
          revenue,
          cost,
          profit,
          margin,
        };
      });

      // 模拟产品利润数据
      const mockProductProfits: ProductProfit[] = [
        {
          id: '1',
          name: 'Product 1',
          revenue: 25000,
          cost: 15000,
          profit: 10000,
          margin: 40,
          quantity: 100,
        },
        {
          id: '2',
          name: 'Product 2',
          revenue: 30000,
          cost: 20000,
          profit: 10000,
          margin: 33.33,
          quantity: 150,
        },
        {
          id: '3',
          name: 'Product 3',
          revenue: 20000,
          cost: 12000,
          profit: 8000,
          margin: 40,
          quantity: 80,
        },
        {
          id: '4',
          name: 'Product 4',
          revenue: 15000,
          cost: 9000,
          profit: 6000,
          margin: 40,
          quantity: 60,
        },
      ];

      // 模拟类别利润数据
      const mockCategoryProfits: CategoryProfit[] = [
        { name: 'Electronics', value: 40 },
        { name: 'Clothing', value: 30 },
        { name: 'Home Goods', value: 20 },
        { name: 'Other', value: 10 },
      ];

      setProfitData(mockProfitData);
      setProductProfits(mockProductProfits);
      setCategoryProfits(mockCategoryProfits);
      setLoading(false);
    }, 500);
  };

  const handleExport = () => {
    // 模拟导出功能
    alert('报表已导出');
  };

  const columns = [
    {
      title: '产品名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '收入',
      dataIndex: 'revenue',
      key: 'revenue',
      render: (revenue: number) => `$${revenue.toFixed(2)}`,
    },
    {
      title: '成本',
      dataIndex: 'cost',
      key: 'cost',
      render: (cost: number) => `$${cost.toFixed(2)}`,
    },
    {
      title: '利润',
      dataIndex: 'profit',
      key: 'profit',
      render: (profit: number) => `$${profit.toFixed(2)}`,
    },
    {
      title: '利润率',
      dataIndex: 'margin',
      key: 'margin',
      render: (margin: number) => `${margin.toFixed(2)}%`,
    },
    {
      title: '销量',
      dataIndex: 'quantity',
      key: 'quantity',
    },
  ];

  const COLORS = ['#0088FE', '#00C49F', '#FFBB28', '#FF8042'];

  const totalRevenue = profitData.reduce((sum, item) => sum + item.revenue, 0);
  const totalCost = profitData.reduce((sum, item) => sum + item.cost, 0);
  const totalProfit = profitData.reduce((sum, item) => sum + item.profit, 0);
  const averageMargin = profitData.length > 0 ? (totalProfit / totalRevenue) * 100 : 0;

  return (
    <div className="profit-report">
      <div className="page-header">
        <h1>利润报表</h1>
        <Button
          type="primary"
          icon={<DownloadOutlined />}
          onClick={handleExport}
        >
          导出
        </Button>
      </div>

      <div className="filter-section" style={{ marginBottom: 24, display: 'flex', gap: 16, flexWrap: 'wrap' }}>
        <Select
          placeholder="时间范围"
          style={{ width: 120 }}
          onChange={setTimeRange}
        >
          <Option value="week">周</Option>
          <Option value="month">月</Option>
          <Option value="quarter">季度</Option>
          <Option value="year">年</Option>
        </Select>
        <RangePicker
          style={{ width: 300 }}
          onChange={setDateRange}
        />
        <Select
          placeholder="类别"
          style={{ width: 120 }}
          onChange={setSelectedCategory}
        >
          <Option value="all">全部</Option>
          <Option value="Electronics">Electronics</Option>
          <Option value="Clothing">Clothing</Option>
          <Option value="Home Goods">Home Goods</Option>
        </Select>
        <Button
          icon={<RefreshOutlined />}
          onClick={fetchProfitData}
        >
          刷新
        </Button>
      </div>

      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={6}>
          <Card>
            <h3>总收入</h3>
            <p style={{ fontSize: '24px', fontWeight: 'bold' }}>${totalRevenue.toFixed(2)}</p>
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <h3>总成本</h3>
            <p style={{ fontSize: '24px', fontWeight: 'bold', color: '#cf1322' }}>${totalCost.toFixed(2)}</p>
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <h3>总利润</h3>
            <p style={{ fontSize: '24px', fontWeight: 'bold', color: '#3f8600' }}>${totalProfit.toFixed(2)}</p>
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <h3>平均利润率</h3>
            <p style={{ fontSize: '24px', fontWeight: 'bold', color: '#3f8600' }}>{averageMargin.toFixed(2)}%</p>
          </Card>
        </Col>
      </Row>

      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={12}>
          <Card title="利润趋势">
            <ResponsiveContainer width="100%" height={400}>
              <LineChart data={profitData}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="date" />
                <YAxis />
                <Tooltip />
                <Legend />
                <Line type="monotone" dataKey="revenue" stroke="#8884d8" name="收入" />
                <Line type="monotone" dataKey="cost" stroke="#82ca9d" name="成本" />
                <Line type="monotone" dataKey="profit" stroke="#ff7300" name="利润" />
              </LineChart>
            </ResponsiveContainer>
          </Card>
        </Col>
        <Col span={12}>
          <Card title="类别利润分布">
            <ResponsiveContainer width="100%" height={400}>
              <PieChart>
                <Pie
                  data={categoryProfits}
                  cx="50%"
                  cy="50%"
                  labelLine={false}
                  label={({ name, percent }) => `${name}: ${(percent * 100).toFixed(0)}%`}
                  outerRadius={150}
                  fill="#8884d8"
                  dataKey="value"
                >
                  {categoryProfits.map((entry, index) => (
                    <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                  ))}
                </Pie>
                <Tooltip />
                <Legend />
              </PieChart>
            </ResponsiveContainer>
          </Card>
        </Col>
      </Row>

      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={24}>
          <Card title="产品利润明细">
            <Table
              columns={columns}
              dataSource={productProfits}
              loading={loading}
              rowKey="id"
              pagination={{
                pageSize: 10,
                showSizeChanger: true,
              }}
            />
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default ProfitReport;