import React, { useState, useEffect } from 'react';
import { Card, Row, Col, Table, Input, Select, DatePicker, Button } from 'antd';
import { SearchOutlined, BarChartOutlined, LineChartOutlined, PieChartOutlined } from '@ant-design/icons';
import { BarChart, Bar, LineChart, Line, PieChart, Pie, Cell, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts';
import { marketingDataSource, Competitor } from '@/services/marketingDataSource';

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

interface ProductComparison {
  product: string;
  ourPrice: number;
  competitorPrice: number;
  priceDifference: number;
  ourRating: number;
  competitorRating: number;
}

const Competitors: React.FC = () => {
  const [competitors, setCompetitors] = useState<Competitor[]>([]);
  const [productComparisons, setProductComparisons] = useState<ProductComparison[]>([]);
  const [loading, setLoading] = useState(false);
  const [filters, setFilters] = useState({
    category: '',
    search: '',
    dateRange: null as any,
  });

  useEffect(() => {
    fetchCompetitorData();
  }, [filters]);

  const fetchCompetitorData = async () => {
    setLoading(true);
    // 模拟API调用
    setTimeout(() => {
      // 模拟竞争对手数据
      const mockCompetitors: Competitor[] = [
        {
          id: '1',
          name: 'Competitor A',
          category: 'Electronics',
          marketShare: 30,
          price: 199.99,
          rating: 4.5,
          reviewCount: 1000,
          website: 'https://competitor-a.com',
          socialFollowers: 100000,
        },
        {
          id: '2',
          name: 'Competitor B',
          category: 'Electronics',
          marketShare: 25,
          price: 189.99,
          rating: 4.2,
          reviewCount: 800,
          website: 'https://competitor-b.com',
          socialFollowers: 80000,
        },
        {
          id: '3',
          name: 'Competitor C',
          category: 'Electronics',
          marketShare: 20,
          price: 209.99,
          rating: 4.7,
          reviewCount: 1200,
          website: 'https://competitor-c.com',
          socialFollowers: 120000,
        },
        {
          id: '4',
          name: 'Competitor D',
          category: 'Electronics',
          marketShare: 15,
          price: 179.99,
          rating: 4.0,
          reviewCount: 600,
          website: 'https://competitor-d.com',
          socialFollowers: 60000,
        },
        {
          id: '5',
          name: 'Competitor E',
          category: 'Electronics',
          marketShare: 10,
          price: 219.99,
          rating: 4.8,
          reviewCount: 1500,
          website: 'https://competitor-e.com',
          socialFollowers: 150000,
        },
      ];

      // 模拟产品比较数据
      const mockProductComparisons: ProductComparison[] = [
        {
          product: 'Product 1',
          ourPrice: 99.99,
          competitorPrice: 109.99,
          priceDifference: -10,
          ourRating: 4.5,
          competitorRating: 4.2,
        },
        {
          product: 'Product 2',
          ourPrice: 199.99,
          competitorPrice: 189.99,
          priceDifference: 10,
          ourRating: 4.3,
          competitorRating: 4.5,
        },
        {
          product: 'Product 3',
          ourPrice: 299.99,
          competitorPrice: 319.99,
          priceDifference: -20,
          ourRating: 4.7,
          competitorRating: 4.4,
        },
        {
          product: 'Product 4',
          ourPrice: 149.99,
          competitorPrice: 149.99,
          priceDifference: 0,
          ourRating: 4.4,
          competitorRating: 4.3,
        },
      ];

      setCompetitors(mockCompetitors);
      setProductComparisons(mockProductComparisons);
      setLoading(false);
    }, 500);
  };

  const columns = [
    {
      title: '竞争对手',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '类别',
      dataIndex: 'category',
      key: 'category',
    },
    {
      title: '市场份额',
      dataIndex: 'marketShare',
      key: 'marketShare',
      render: (share: number) => `${share}%`,
    },
    {
      title: '价格',
      dataIndex: 'price',
      key: 'price',
      render: (price: number) => `$${price.toFixed(2)}`,
    },
    {
      title: '评分',
      dataIndex: 'rating',
      key: 'rating',
    },
    {
      title: '评论数',
      dataIndex: 'reviewCount',
      key: 'reviewCount',
    },
    {
      title: '社交媒体粉丝',
      dataIndex: 'socialFollowers',
      key: 'socialFollowers',
    },
  ];

  const marketShareData = competitors.map(competitor => ({
    name: competitor.name,
    value: competitor.marketShare,
  }));

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

  return (
    <div className="competitors">
      <div className="page-header">
        <h1>竞争对手分析</h1>
      </div>

      <div className="filter-section" style={{ marginBottom: 24, display: 'flex', gap: 16, flexWrap: 'wrap' }}>
        <Search
          placeholder="搜索竞争对手名称"
          style={{ width: 300 }}
          onChange={(e) => setFilters({ ...filters, search: e.target.value })}
        />
        <Select
          placeholder="类别"
          style={{ width: 120 }}
          onChange={(value) => setFilters({ ...filters, category: value })}
        >
          <Option value="">全部</Option>
          <Option value="Electronics">Electronics</Option>
          <Option value="Clothing">Clothing</Option>
          <Option value="Home Goods">Home Goods</Option>
        </Select>
        <RangePicker
          style={{ width: 300 }}
          onChange={(dates) => setFilters({ ...filters, dateRange: dates })}
        />
        <Button
          icon={<SearchOutlined />}
          onClick={fetchCompetitorData}
        >
          筛选
        </Button>
      </div>

      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={12}>
          <Card title="市场份额分析">
            <ResponsiveContainer width="100%" height={400}>
              <PieChart>
                <Pie
                  data={marketShareData}
                  cx="50%"
                  cy="50%"
                  labelLine={false}
                  label={({ name, percent }) => `${name}: ${(percent * 100).toFixed(0)}%`}
                  outerRadius={150}
                  fill="#8884d8"
                  dataKey="value"
                >
                  {marketShareData.map((entry, index) => (
                    <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                  ))}
                </Pie>
                <Tooltip />
                <Legend />
              </PieChart>
            </ResponsiveContainer>
          </Card>
        </Col>
        <Col span={12}>
          <Card title="价格比较">
            <ResponsiveContainer width="100%" height={400}>
              <BarChart data={productComparisons}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="product" />
                <YAxis />
                <Tooltip />
                <Legend />
                <Bar dataKey="ourPrice" fill="#8884d8" name="我们的价格" />
                <Bar dataKey="competitorPrice" fill="#82ca9d" name="竞争对手价格" />
              </BarChart>
            </ResponsiveContainer>
          </Card>
        </Col>
      </Row>

      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={12}>
          <Card title="评分比较">
            <ResponsiveContainer width="100%" height={400}>
              <BarChart data={productComparisons}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="product" />
                <YAxis />
                <Tooltip />
                <Legend />
                <Bar dataKey="ourRating" fill="#8884d8" name="我们的评分" />
                <Bar dataKey="competitorRating" fill="#82ca9d" name="竞争对手评分" />
              </BarChart>
            </ResponsiveContainer>
          </Card>
        </Col>
        <Col span={12}>
          <Card title="价格差异">
            <ResponsiveContainer width="100%" height={400}>
              <LineChart data={productComparisons}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="product" />
                <YAxis />
                <Tooltip />
                <Legend />
                <Line type="monotone" dataKey="priceDifference" stroke="#ff7300" name="价格差异" />
              </LineChart>
            </ResponsiveContainer>
          </Card>
        </Col>
      </Row>

      <Card title="竞争对手列表">
        <Table
          columns={columns}
          dataSource={competitors}
          loading={loading}
          rowKey="id"
          pagination={{
            pageSize: 10,
            showSizeChanger: true,
          }}
        />
      </Card>
    </div>
  );
};

export default Competitors;