import {
  useState,
  useEffect,
  Card,
  Row,
  Col,
  Table,
  Input,
  Select,
  DatePicker,
  Button,
  SearchOutlined,
  BarChartOutlined,
  LineChartOutlined,
  PieChartOutlined,
  Option,
  RangePicker,
  Search,
  FC,
} from '@/imports';
import { BarChart, Bar, LineChart, Line, PieChart, Pie, Cell, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts';
import { marketingDataSource, Competitor } from '@/services/marketingDataSource';

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

const Competitors: 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',
          platform: 'Amazon',
          products: 150,
          marketShare: 30,
          avgPrice: 199.99,
          avgRating: 4.5,
          reviewCount: 1000,
          lastUpdated: '2026-03-20',
          trackedProducts: ['SKU-001', 'SKU-002'],
          website: 'https://competitor-a.com',
          socialFollowers: 100000,
        },
        {
          id: '2',
          name: 'Competitor B',
          platform: 'Amazon',
          products: 120,
          marketShare: 25,
          avgPrice: 189.99,
          avgRating: 4.2,
          reviewCount: 800,
          lastUpdated: '2026-03-19',
          trackedProducts: ['SKU-003', 'SKU-004'],
          website: 'https://competitor-b.com',
          socialFollowers: 80000,
        },
        {
          id: '3',
          name: 'Competitor C',
          platform: 'eBay',
          products: 200,
          marketShare: 20,
          avgPrice: 209.99,
          avgRating: 4.7,
          reviewCount: 1200,
          lastUpdated: '2026-03-18',
          trackedProducts: ['SKU-005'],
          website: 'https://competitor-c.com',
          socialFollowers: 120000,
        },
        {
          id: '4',
          name: 'Competitor D',
          platform: 'Shopify',
          products: 80,
          marketShare: 15,
          avgPrice: 179.99,
          avgRating: 4.0,
          reviewCount: 600,
          lastUpdated: '2026-03-17',
          trackedProducts: ['SKU-006', 'SKU-007'],
          website: 'https://competitor-d.com',
          socialFollowers: 60000,
        },
        {
          id: '5',
          name: 'Competitor E',
          platform: 'Walmart',
          products: 100,
          marketShare: 10,
          avgPrice: 219.99,
          avgRating: 4.8,
          reviewCount: 1500,
          lastUpdated: '2026-03-16',
          trackedProducts: ['SKU-008'],
          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: 'platform',
      key: 'platform',
    },
    {
      title: '产品数',
      dataIndex: 'products',
      key: 'products',
    },
    {
      title: '市场份额',
      dataIndex: 'marketShare',
      key: 'marketShare',
      render: (share: number | undefined) => share != null ? `${share}%` : '-',
    },
    {
      title: '平均价格',
      dataIndex: 'avgPrice',
      key: 'avgPrice',
      render: (price: number | undefined) => price != null ? `$${price.toFixed(2)}` : '-',
    },
    {
      title: '平均评分',
      dataIndex: 'avgRating',
      key: 'avgRating',
      render: (rating: number | undefined) => rating != null ? rating.toFixed(1) : '-',
    },
    {
      title: '评论数',
      dataIndex: 'reviewCount',
      key: 'reviewCount',
      render: (count: number | undefined) => count != null ? count.toLocaleString() : '-',
    },
    {
      title: '社交媒体粉丝',
      dataIndex: 'socialFollowers',
      key: 'socialFollowers',
      render: (followers: number | undefined) => followers != null ? followers.toLocaleString() : '-',
    },
  ];

  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 || 0) * 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;