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 } from 'recharts';
import { DownloadOutlined, RefreshOutlined } from '@ant-design/icons';
import { reportsDataSource, PerformanceMetric } from '@/services/reportsDataSource';

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

interface PerformanceData {
  date: string;
  sales: number;
  orders: number;
  conversionRate: number;
  averageOrderValue: number;
  customers: number;
}

interface ChannelPerformance {
  id: string;
  name: string;
  sales: number;
  orders: number;
  conversionRate: number;
  ctr: number;
  cpc: number;
  roi: number;
}

const PerformanceReport: React.FC = () => {
  const [performanceData, setPerformanceData] = useState<PerformanceData[]>([]);
  const [channelPerformance, setChannelPerformance] = useState<ChannelPerformance[]>([]);
  const [loading, setLoading] = useState(false);
  const [timeRange, setTimeRange] = useState('month');
  const [dateRange, setDateRange] = useState<any>(null);
  const [selectedChannel, setSelectedChannel] = useState('all');

  useEffect(() => {
    fetchPerformanceData();
  }, [timeRange, dateRange, selectedChannel]);

  const fetchPerformanceData = async () => {
    setLoading(true);
    // 模拟API调用
    setTimeout(() => {
      // 模拟绩效数据
      const mockPerformanceData: PerformanceData[] = Array.from({ length: 12 }, (_, i) => {
        const month = i + 1;
        const sales = Math.random() * 100000 + 50000;
        const orders = Math.random() * 500 + 100;
        const conversionRate = Math.random() * 5 + 2;
        const averageOrderValue = sales / orders;
        const customers = Math.random() * 300 + 50;
        return {
          date: `2026-${String(month).padStart(2, '0')}`,
          sales,
          orders,
          conversionRate,
          averageOrderValue,
          customers,
        };
      });

      // 模拟渠道绩效数据
      const mockChannelPerformance: ChannelPerformance[] = [
        {
          id: '1',
          name: 'Facebook',
          sales: 30000,
          orders: 150,
          conversionRate: 3.5,
          ctr: 2.5,
          cpc: 1.5,
          roi: 3.0,
        },
        {
          id: '2',
          name: 'Google',
          sales: 25000,
          orders: 125,
          conversionRate: 4.0,
          ctr: 1.8,
          cpc: 2.0,
          roi: 2.5,
        },
        {
          id: '3',
          name: 'Instagram',
          sales: 20000,
          orders: 100,
          conversionRate: 3.0,
          ctr: 3.0,
          cpc: 1.2,
          roi: 3.5,
        },
        {
          id: '4',
          name: 'TikTok',
          sales: 15000,
          orders: 75,
          conversionRate: 2.5,
          ctr: 4.0,
          cpc: 0.8,
          roi: 4.0,
        },
      ];

      setPerformanceData(mockPerformanceData);
      setChannelPerformance(mockChannelPerformance);
      setLoading(false);
    }, 500);
  };

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

  const columns = [
    {
      title: '渠道',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '销售',
      dataIndex: 'sales',
      key: 'sales',
      render: (sales: number) => `$${sales.toFixed(2)}`,
    },
    {
      title: '订单数',
      dataIndex: 'orders',
      key: 'orders',
    },
    {
      title: '转化率',
      dataIndex: 'conversionRate',
      key: 'conversionRate',
      render: (rate: number) => `${rate.toFixed(2)}%`,
    },
    {
      title: '点击率',
      dataIndex: 'ctr',
      key: 'ctr',
      render: (rate: number) => `${rate.toFixed(2)}%`,
    },
    {
      title: '点击成本',
      dataIndex: 'cpc',
      key: 'cpc',
      render: (cpc: number) => `$${cpc.toFixed(2)}`,
    },
    {
      title: 'ROI',
      dataIndex: 'roi',
      key: 'roi',
      render: (roi: number) => `${roi.toFixed(2)}x`,
    },
  ];

  const totalSales = performanceData.reduce((sum, item) => sum + item.sales, 0);
  const totalOrders = performanceData.reduce((sum, item) => sum + item.orders, 0);
  const totalCustomers = performanceData.reduce((sum, item) => sum + item.customers, 0);
  const averageOrderValue = totalOrders > 0 ? totalSales / totalOrders : 0;
  const averageConversionRate = performanceData.length > 0 ? 
    performanceData.reduce((sum, item) => sum + item.conversionRate, 0) / performanceData.length : 0;

  return (
    <div className="performance-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={setSelectedChannel}
        >
          <Option value="all">全部</Option>
          <Option value="Facebook">Facebook</Option>
          <Option value="Google">Google</Option>
          <Option value="Instagram">Instagram</Option>
          <Option value="TikTok">TikTok</Option>
        </Select>
        <Button
          icon={<RefreshOutlined />}
          onClick={fetchPerformanceData}
        >
          刷新
        </Button>
      </div>

      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={6}>
          <Card>
            <h3>总销售</h3>
            <p style={{ fontSize: '24px', fontWeight: 'bold' }}>${totalSales.toFixed(2)}</p>
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <h3>总订单</h3>
            <p style={{ fontSize: '24px', fontWeight: 'bold' }}>{totalOrders}</p>
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <h3>平均订单价值</h3>
            <p style={{ fontSize: '24px', fontWeight: 'bold' }}>${averageOrderValue.toFixed(2)}</p>
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <h3>平均转化率</h3>
            <p style={{ fontSize: '24px', fontWeight: 'bold', color: '#3f8600' }}>{averageConversionRate.toFixed(2)}%</p>
          </Card>
        </Col>
      </Row>

      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={12}>
          <Card title="销售与订单趋势">
            <ResponsiveContainer width="100%" height={400}>
              <LineChart data={performanceData}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="date" />
                <YAxis />
                <Tooltip />
                <Legend />
                <Line type="monotone" dataKey="sales" stroke="#8884d8" name="销售" />
                <Line type="monotone" dataKey="orders" stroke="#82ca9d" name="订单" />
              </LineChart>
            </ResponsiveContainer>
          </Card>
        </Col>
        <Col span={12}>
          <Card title="转化率与平均订单价值">
            <ResponsiveContainer width="100%" height={400}>
              <LineChart data={performanceData}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="date" />
                <YAxis />
                <Tooltip />
                <Legend />
                <Line type="monotone" dataKey="conversionRate" stroke="#ff7300" name="转化率" />
                <Line type="monotone" dataKey="averageOrderValue" stroke="#0088FE" name="平均订单价值" />
              </LineChart>
            </ResponsiveContainer>
          </Card>
        </Col>
      </Row>

      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={24}>
          <Card title="渠道绩效明细">
            <Table
              columns={columns}
              dataSource={channelPerformance}
              loading={loading}
              rowKey="id"
              pagination={{
                pageSize: 10,
                showSizeChanger: true,
              }}
            />
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default PerformanceReport;