import React, { useState, useEffect, useCallback } from 'react';
import {
  Card,
  Row,
  Col,
  Table,
  Button,
  Space,
  Tag,
  Statistic,
  Progress,
  Tabs,
  Form,
  InputNumber,
  Select,
  Switch,
  Modal,
  message,
  Badge,
  Tooltip,
  Typography,
  Divider,
  List,
  Avatar,
  Alert,
  Spin,
} from 'antd';
import {
  DollarOutlined,
  RiseOutlined,
  FallOutlined,
  LineChartOutlined,
  BellOutlined,
  SettingOutlined,
  SyncOutlined,
  EyeOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  WarningOutlined,
  TrophyOutlined,
  AimOutlined,
} from '@ant-design/icons';
import moment from 'moment';

const { Title, Text, Paragraph } = Typography;
const { TabPane } = Tabs;
const { Option } = Select;

interface PricingConfig {
  id: string;
  product_id: string;
  product_name: string;
  base_price: number;
  min_price: number;
  max_price: number;
  cost_price: number;
  strategy: 'GAME_THEORY' | 'COMPETITION' | 'DEMAND_BASED' | 'COST_PLUS' | 'DYNAMIC';
  auto_adjust: boolean;
  adjust_frequency: 'HOURLY' | 'DAILY' | 'WEEKLY';
  max_adjust_percent: number;
  min_profit_margin: number;
  enabled: boolean;
}

interface PricingDecision {
  id: string;
  product_id: string;
  product_name: string;
  current_price: number;
  suggested_price: number;
  price_change: number;
  change_percent: number;
  adjustment_direction: 'INCREASE' | 'DECREASE' | 'MAINTAIN';
  strategy_used: string;
  predicted_impact: {
    revenue_change: number;
    profit_change: number;
    sales_change: number;
    confidence: number;
  };
  status: 'PENDING' | 'EXECUTED' | 'REJECTED' | 'EXPIRED';
  created_at: string;
}

interface CompetitorPrice {
  id: string;
  competitor_name: string;
  platform: string;
  price: number;
  shipping_cost: number;
  total_price: number;
  stock_status: 'IN_STOCK' | 'LOW_STOCK' | 'OUT_OF_STOCK';
  rating: number;
  review_count: number;
  last_checked: string;
}

interface PriceAlert {
  id: string;
  alert_type: 'PRICE_DROP' | 'PRICE_INCREASE' | 'OUT_OF_STOCK' | 'BACK_IN_STOCK' | 'NEW_COMPETITOR';
  severity: 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL';
  competitor_name: string;
  change_description: string;
  is_read: boolean;
  created_at: string;
}

interface MarketAnalysis {
  price_range: {
    min: number;
    max: number;
    avg: number;
    median: number;
  };
  our_position: {
    rank: number;
    percentile: number;
    price_gap_to_lowest: number;
    price_gap_to_avg: number;
  };
  recommendations: {
    optimal_price: number;
    expected_position: number;
    reasoning: string;
  };
}

const MOCK_CONFIGS: PricingConfig[] = [
  {
    id: 'PC-001',
    product_id: 'P-001',
    product_name: 'Wireless Bluetooth Earbuds Pro',
    base_price: 49.99,
    min_price: 39.99,
    max_price: 69.99,
    cost_price: 25.00,
    strategy: 'COMPETITION',
    auto_adjust: true,
    adjust_frequency: 'DAILY',
    max_adjust_percent: 10,
    min_profit_margin: 20,
    enabled: true,
  },
  {
    id: 'PC-002',
    product_id: 'P-002',
    product_name: 'Smart Watch Series X',
    base_price: 199.99,
    min_price: 149.99,
    max_price: 299.99,
    cost_price: 95.00,
    strategy: 'GAME_THEORY',
    auto_adjust: true,
    adjust_frequency: 'HOURLY',
    max_adjust_percent: 15,
    min_profit_margin: 25,
    enabled: true,
  },
  {
    id: 'PC-003',
    product_id: 'P-003',
    product_name: 'Portable Power Bank 20000mAh',
    base_price: 29.99,
    min_price: 24.99,
    max_price: 39.99,
    cost_price: 12.00,
    strategy: 'DEMAND_BASED',
    auto_adjust: false,
    adjust_frequency: 'WEEKLY',
    max_adjust_percent: 8,
    min_profit_margin: 15,
    enabled: true,
  },
];

const MOCK_DECISIONS: PricingDecision[] = [
  {
    id: 'PD-001',
    product_id: 'P-001',
    product_name: 'Wireless Bluetooth Earbuds Pro',
    current_price: 49.99,
    suggested_price: 47.49,
    price_change: -2.50,
    change_percent: -5.0,
    adjustment_direction: 'DECREASE',
    strategy_used: 'COMPETITION',
    predicted_impact: {
      revenue_change: 3.2,
      profit_change: -1.5,
      sales_change: 8.5,
      confidence: 0.85,
    },
    status: 'PENDING',
    created_at: '2026-03-19T10:30:00Z',
  },
  {
    id: 'PD-002',
    product_id: 'P-002',
    product_name: 'Smart Watch Series X',
    current_price: 199.99,
    suggested_price: 219.99,
    price_change: 20.00,
    change_percent: 10.0,
    adjustment_direction: 'INCREASE',
    strategy_used: 'GAME_THEORY',
    predicted_impact: {
      revenue_change: 8.5,
      profit_change: 12.3,
      sales_change: -2.1,
      confidence: 0.78,
    },
    status: 'PENDING',
    created_at: '2026-03-19T11:00:00Z',
  },
];

const MOCK_COMPETITORS: CompetitorPrice[] = [
  {
    id: 'CP-001',
    competitor_name: 'TechMart Official',
    platform: 'Amazon',
    price: 44.99,
    shipping_cost: 0,
    total_price: 44.99,
    stock_status: 'IN_STOCK',
    rating: 4.5,
    review_count: 1250,
    last_checked: '2026-03-19T09:00:00Z',
  },
  {
    id: 'CP-002',
    competitor_name: 'GadgetWorld',
    platform: 'Amazon',
    price: 46.99,
    shipping_cost: 2.99,
    total_price: 49.98,
    stock_status: 'IN_STOCK',
    rating: 4.3,
    review_count: 856,
    last_checked: '2026-03-19T09:00:00Z',
  },
  {
    id: 'CP-003',
    competitor_name: 'ElectroDeal',
    platform: 'eBay',
    price: 42.50,
    shipping_cost: 4.99,
    total_price: 47.49,
    stock_status: 'LOW_STOCK',
    rating: 4.1,
    review_count: 423,
    last_checked: '2026-03-19T08:30:00Z',
  },
  {
    id: 'CP-004',
    competitor_name: 'BestBuy Direct',
    platform: 'Walmart',
    price: 48.99,
    shipping_cost: 0,
    total_price: 48.99,
    stock_status: 'IN_STOCK',
    rating: 4.6,
    review_count: 2100,
    last_checked: '2026-03-19T09:15:00Z',
  },
];

const MOCK_ALERTS: PriceAlert[] = [
  {
    id: 'PA-001',
    alert_type: 'PRICE_DROP',
    severity: 'HIGH',
    competitor_name: 'TechMart Official',
    change_description: 'TechMart Official 价格下降 8.2%，从 $48.99 降至 $44.99',
    is_read: false,
    created_at: '2026-03-19T08:45:00Z',
  },
  {
    id: 'PA-002',
    alert_type: 'NEW_COMPETITOR',
    severity: 'MEDIUM',
    competitor_name: 'BudgetElectronics',
    change_description: '发现新竞品: BudgetElectronics 在 Amazon 上架',
    is_read: false,
    created_at: '2026-03-19T07:30:00Z',
  },
  {
    id: 'PA-003',
    alert_type: 'OUT_OF_STOCK',
    severity: 'LOW',
    competitor_name: 'ElectroDeal',
    change_description: 'ElectroDeal 库存紧张，仅剩少量库存',
    is_read: true,
    created_at: '2026-03-18T16:20:00Z',
  },
];

const MOCK_MARKET_ANALYSIS: MarketAnalysis = {
  price_range: {
    min: 42.50,
    max: 54.99,
    avg: 47.74,
    median: 47.49,
  },
  our_position: {
    rank: 3,
    percentile: 60,
    price_gap_to_lowest: 7.49,
    price_gap_to_avg: 2.25,
  },
  recommendations: {
    optimal_price: 45.35,
    expected_position: 2,
    reasoning: '建议定价低于市场均价5%，可在保持利润的同时获得价格竞争优势',
  },
};

const strategyOptions = [
  { value: 'GAME_THEORY', label: '博弈定价', desc: '基于博弈论的最优定价策略' },
  { value: 'COMPETITION', label: '竞争定价', desc: '根据竞争对手价格调整' },
  { value: 'DEMAND_BASED', label: '需求定价', desc: '基于需求弹性动态定价' },
  { value: 'COST_PLUS', label: '成本加成', desc: '成本基础上加固定利润率' },
  { value: 'DYNAMIC', label: '动态定价', desc: '综合多因素的智能定价' },
];

const DynamicPricing: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [activeTab, setActiveTab] = useState('overview');
  const [configs, setConfigs] = useState<PricingConfig[]>(MOCK_CONFIGS);
  const [decisions, setDecisions] = useState<PricingDecision[]>(MOCK_DECISIONS);
  const [competitors, setCompetitors] = useState<CompetitorPrice[]>(MOCK_COMPETITORS);
  const [alerts, setAlerts] = useState<PriceAlert[]>(MOCK_ALERTS);
  const [marketAnalysis] = useState<MarketAnalysis>(MOCK_MARKET_ANALYSIS);
  const [selectedProduct, setSelectedProduct] = useState<string | null>(null);
  const [configModalVisible, setConfigModalVisible] = useState(false);
  const [decisionModalVisible, setDecisionModalVisible] = useState(false);
  const [selectedDecision, setSelectedDecision] = useState<PricingDecision | null>(null);
  const [form] = Form.useForm();

  const fetchData = useCallback(async () => {
    setLoading(true);
    try {
      await new Promise(resolve => setTimeout(resolve, 500));
    } catch (error) {
      message.error('加载数据失败');
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchData();
  }, [fetchData]);

  const handleExecuteDecision = (decisionId: string) => {
    Modal.confirm({
      title: '确认执行定价决策',
      content: '执行后将自动调整商品价格，是否继续？',
      onOk: () => {
        setDecisions(prev =>
          prev.map(d =>
            d.id === decisionId ? { ...d, status: 'EXECUTED' } : d
          )
        );
        message.success('定价决策已执行');
      },
    });
  };

  const handleRejectDecision = (decisionId: string) => {
    setDecisions(prev =>
      prev.map(d =>
        d.id === decisionId ? { ...d, status: 'REJECTED' } : d
      )
    );
    message.info('定价决策已拒绝');
  };

  const handleMarkAlertRead = (alertId: string) => {
    setAlerts(prev =>
      prev.map(a =>
        a.id === alertId ? { ...a, is_read: true } : a
      )
    );
  };

  const handleSaveConfig = () => {
    form.validateFields().then(values => {
      message.success('定价配置已保存');
      setConfigModalVisible(false);
    });
  };

  const renderOverview = () => (
    <div>
      <Row gutter={[16, 16]}>
        <Col xs={24} sm={12} lg={6}>
          <Card>
            <Statistic
              title="监控商品数"
              value={configs.length}
              prefix={<EyeOutlined />}
              valueStyle={{ color: '#1890ff' }}
            />
            <div style={{ marginTop: 8 }}>
              <Text type="secondary">已启用自动调价: {configs.filter(c => c.auto_adjust).length}</Text>
            </div>
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card>
            <Statistic
              title="待审核决策"
              value={decisions.filter(d => d.status === 'PENDING').length}
              prefix={<AimOutlined />}
              valueStyle={{ color: '#faad14' }}
            />
            <div style={{ marginTop: 8 }}>
              <Progress
                percent={75}
                size="small"
                format={() => '今日完成率'}
              />
            </div>
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card>
            <Statistic
              title="竞品监控"
              value={competitors.length}
              prefix={<LineChartOutlined />}
              valueStyle={{ color: '#52c41a' }}
            />
            <div style={{ marginTop: 8 }}>
              <Text type="secondary">覆盖 {new Set(competitors.map(c => c.platform)).size} 个平台</Text>
            </div>
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card>
            <Statistic
              title="未读预警"
              value={alerts.filter(a => !a.is_read).length}
              prefix={<BellOutlined />}
              valueStyle={{ color: alerts.filter(a => !a.is_read).length > 0 ? '#ff4d4f' : '#52c41a' }}
            />
            <div style={{ marginTop: 8 }}>
              <Badge status={alerts.filter(a => !a.is_read).length > 0 ? 'error' : 'success'} text="预警状态" />
            </div>
          </Card>
        </Col>
      </Row>

      <Card
        title="待审核定价决策"
        style={{ marginTop: 16 }}
        extra={
          <Space>
            <Button icon={<SyncOutlined />} onClick={fetchData}>
              刷新
            </Button>
          </Space>
        }
      >
        <Table
          dataSource={decisions.filter(d => d.status === 'PENDING')}
          rowKey="id"
          pagination={false}
          columns={[
            {
              title: '商品名称',
              dataIndex: 'product_name',
              key: 'product_name',
              width: 200,
            },
            {
              title: '当前价格',
              dataIndex: 'current_price',
              key: 'current_price',
              width: 100,
              render: (v: number) => `$${v.toFixed(2)}`,
            },
            {
              title: '建议价格',
              dataIndex: 'suggested_price',
              key: 'suggested_price',
              width: 100,
              render: (v: number, record: PricingDecision) => (
                <Text type={record.adjustment_direction === 'INCREASE' ? 'success' : record.adjustment_direction === 'DECREASE' ? 'danger' : undefined}>
                  ${v.toFixed(2)}
                </Text>
              ),
            },
            {
              title: '变化',
              dataIndex: 'change_percent',
              key: 'change_percent',
              width: 100,
              render: (v: number, record: PricingDecision) => (
                <Tag color={record.adjustment_direction === 'INCREASE' ? 'green' : record.adjustment_direction === 'DECREASE' ? 'red' : 'default'}>
                  {record.adjustment_direction === 'INCREASE' ? <RiseOutlined /> : <FallOutlined />} {v.toFixed(1)}%
                </Tag>
              ),
            },
            {
              title: '策略',
              dataIndex: 'strategy_used',
              key: 'strategy_used',
              width: 120,
              render: (v: string) => {
                const strategy = strategyOptions.find(s => s.value === v);
                return <Tag>{strategy?.label || v}</Tag>;
              },
            },
            {
              title: '预测影响',
              key: 'impact',
              width: 200,
              render: (_: any, record: PricingDecision) => (
                <Space direction="vertical" size="small">
                  <Text type="secondary" style={{ fontSize: 12 }}>
                    收益: <Text type={record.predicted_impact.revenue_change > 0 ? 'success' : 'danger'}>+{record.predicted_impact.revenue_change}%</Text>
                  </Text>
                  <Text type="secondary" style={{ fontSize: 12 }}>
                    利润: <Text type={record.predicted_impact.profit_change > 0 ? 'success' : 'danger'}>{record.predicted_impact.profit_change > 0 ? '+' : ''}{record.predicted_impact.profit_change}%</Text>
                  </Text>
                </Space>
              ),
            },
            {
              title: '置信度',
              dataIndex: ['predicted_impact', 'confidence'],
              key: 'confidence',
              width: 100,
              render: (v: number) => (
                <Progress
                  percent={v * 100}
                  size="small"
                  format={percent => `${percent?.toFixed(0)}%`}
                  strokeColor={v >= 0.8 ? '#52c41a' : v >= 0.6 ? '#faad14' : '#ff4d4f'}
                />
              ),
            },
            {
              title: '创建时间',
              dataIndex: 'created_at',
              key: 'created_at',
              width: 150,
              render: (v: string) => moment(v).format('MM-DD HH:mm'),
            },
            {
              title: '操作',
              key: 'action',
              width: 180,
              fixed: 'right',
              render: (_: any, record: PricingDecision) => (
                <Space>
                  <Button
                    type="primary"
                    size="small"
                    icon={<CheckCircleOutlined />}
                    onClick={() => handleExecuteDecision(record.id)}
                  >
                    执行
                  </Button>
                  <Button
                    size="small"
                    icon={<CloseCircleOutlined />}
                    onClick={() => handleRejectDecision(record.id)}
                  >
                    拒绝
                  </Button>
                </Space>
              ),
            },
          ]}
        />
      </Card>

      <Row gutter={16} style={{ marginTop: 16 }}>
        <Col xs={24} lg={12}>
          <Card title="市场分析" extra={<Tag color="blue">实时</Tag>}>
            <Row gutter={16}>
              <Col span={12}>
                <Statistic
                  title="市场最低价"
                  value={marketAnalysis.price_range.min}
                  prefix="$"
                  precision={2}
                />
              </Col>
              <Col span={12}>
                <Statistic
                  title="市场均价"
                  value={marketAnalysis.price_range.avg}
                  prefix="$"
                  precision={2}
                />
              </Col>
            </Row>
            <Divider />
            <Row gutter={16}>
              <Col span={12}>
                <Statistic
                  title="我们的排名"
                  value={marketAnalysis.our_position.rank}
                  suffix={`/ ${competitors.length + 1}`}
                  prefix={<TrophyOutlined />}
                />
              </Col>
              <Col span={12}>
                <Statistic
                  title="价格百分位"
                  value={marketAnalysis.our_position.percentile}
                  suffix="%"
                />
              </Col>
            </Row>
            <Divider />
            <Alert
              message="AI定价建议"
              description={
                <div>
                  <Paragraph>
                    <Text strong>建议价格: </Text>
                    <Text type="success">${marketAnalysis.recommendations.optimal_price.toFixed(2)}</Text>
                  </Paragraph>
                  <Paragraph>
                    <Text type="secondary">{marketAnalysis.recommendations.reasoning}</Text>
                  </Paragraph>
                </div>
              }
              type="info"
              showIcon
              icon={<DollarOutlined />}
            />
          </Card>
        </Col>
        <Col xs={24} lg={12}>
          <Card
            title="价格预警"
            extra={
              <Badge count={alerts.filter(a => !a.is_read).length}>
                <BellOutlined />
              </Badge>
            }
          >
            <List
              dataSource={alerts.slice(0, 5)}
              renderItem={item => (
                <List.Item
                  actions={[
                    !item.is_read && (
                      <Button type="link" size="small" onClick={() => handleMarkAlertRead(item.id)}>
                        标记已读
                      </Button>
                    ),
                  ]}
                >
                  <List.Item.Meta
                    avatar={
                      <Avatar
                        style={{
                          backgroundColor:
                            item.severity === 'CRITICAL'
                              ? '#ff4d4f'
                              : item.severity === 'HIGH'
                              ? '#faad14'
                              : item.severity === 'MEDIUM'
                              ? '#1890ff'
                              : '#52c41a',
                        }}
                        icon={
                          item.alert_type === 'PRICE_DROP' ? (
                            <FallOutlined />
                          ) : item.alert_type === 'PRICE_INCREASE' ? (
                            <RiseOutlined />
                          ) : (
                            <WarningOutlined />
                          )
                        }
                      />
                    }
                    title={
                      <Space>
                        <Text strong={!item.is_read}>{item.competitor_name}</Text>
                        <Tag color={item.severity === 'CRITICAL' ? 'red' : item.severity === 'HIGH' ? 'orange' : 'blue'}>
                          {item.severity}
                        </Tag>
                      </Space>
                    }
                    description={item.change_description}
                  />
                </List.Item>
              )}
            />
          </Card>
        </Col>
      </Row>
    </div>
  );

  const renderCompetitors = () => (
    <Card
      title="竞品价格监控"
      extra={
        <Space>
          <Select defaultValue="all" style={{ width: 120 }}>
            <Option value="all">全部平台</Option>
            <Option value="Amazon">Amazon</Option>
            <Option value="eBay">eBay</Option>
            <Option value="Walmart">Walmart</Option>
          </Select>
          <Button type="primary" icon={<SyncOutlined />}>
            同步数据
          </Button>
        </Space>
      }
    >
      <Table
        dataSource={competitors}
        rowKey="id"
        columns={[
          {
            title: '竞品名称',
            dataIndex: 'competitor_name',
            key: 'competitor_name',
            render: (v: string) => <Text strong>{v}</Text>,
          },
          {
            title: '平台',
            dataIndex: 'platform',
            key: 'platform',
            render: (v: string) => <Tag>{v}</Tag>,
          },
          {
            title: '商品价格',
            dataIndex: 'price',
            key: 'price',
            render: (v: number) => `$${v.toFixed(2)}`,
          },
          {
            title: '运费',
            dataIndex: 'shipping_cost',
            key: 'shipping_cost',
            render: (v: number) => (v > 0 ? `$${v.toFixed(2)}` : <Tag color="green">免运费</Tag>),
          },
          {
            title: '总价',
            dataIndex: 'total_price',
            key: 'total_price',
            render: (v: number, record: CompetitorPrice) => {
              const ourPrice = 49.99;
              const diff = v - ourPrice;
              return (
                <Space>
                  <Text strong>${v.toFixed(2)}</Text>
                  {diff !== 0 && (
                    <Tag color={diff > 0 ? 'green' : 'red'}>
                      {diff > 0 ? '+' : ''}{diff.toFixed(2)}
                    </Tag>
                  )}
                </Space>
              );
            },
          },
          {
            title: '库存状态',
            dataIndex: 'stock_status',
            key: 'stock_status',
            render: (v: string) => {
              const colors: Record<string, string> = {
                IN_STOCK: 'green',
                LOW_STOCK: 'orange',
                OUT_OF_STOCK: 'red',
              };
              const labels: Record<string, string> = {
                IN_STOCK: '有货',
                LOW_STOCK: '库存紧张',
                OUT_OF_STOCK: '缺货',
              };
              return <Tag color={colors[v]}>{labels[v]}</Tag>;
            },
          },
          {
            title: '评分',
            dataIndex: 'rating',
            key: 'rating',
            render: (v: number, record: CompetitorPrice) => (
              <Space>
                <Text>{v.toFixed(1)}</Text>
                <Text type="secondary">({record.review_count})</Text>
              </Space>
            ),
          },
          {
            title: '最后检查',
            dataIndex: 'last_checked',
            key: 'last_checked',
            render: (v: string) => moment(v).fromNow(),
          },
        ]}
      />
    </Card>
  );

  const renderConfigs = () => (
    <Card
      title="定价策略配置"
      extra={
        <Button type="primary" icon={<SettingOutlined />} onClick={() => setConfigModalVisible(true)}>
          新增配置
        </Button>
      }
    >
      <Table
        dataSource={configs}
        rowKey="id"
        columns={[
          {
            title: '商品名称',
            dataIndex: 'product_name',
            key: 'product_name',
          },
          {
            title: '基础价格',
            dataIndex: 'base_price',
            key: 'base_price',
            render: (v: number) => `$${v.toFixed(2)}`,
          },
          {
            title: '价格区间',
            key: 'price_range',
            render: (_: any, record: PricingConfig) => (
              <Text>
                ${record.min_price.toFixed(2)} - ${record.max_price.toFixed(2)}
              </Text>
            ),
          },
          {
            title: '成本价',
            dataIndex: 'cost_price',
            key: 'cost_price',
            render: (v: number) => `$${v.toFixed(2)}`,
          },
          {
            title: '定价策略',
            dataIndex: 'strategy',
            key: 'strategy',
            render: (v: string) => {
              const strategy = strategyOptions.find(s => s.value === v);
              return (
                <Tooltip title={strategy?.desc}>
                  <Tag color="blue">{strategy?.label || v}</Tag>
                </Tooltip>
              );
            },
          },
          {
            title: '自动调价',
            dataIndex: 'auto_adjust',
            key: 'auto_adjust',
            render: (v: boolean, record: PricingConfig) => (
              <Switch
                checked={v}
                onChange={checked => {
                  setConfigs(prev =>
                    prev.map(c =>
                      c.id === record.id ? { ...c, auto_adjust: checked } : c
                    )
                  );
                }}
              />
            ),
          },
          {
            title: '调价频率',
            dataIndex: 'adjust_frequency',
            key: 'adjust_frequency',
            render: (v: string) => {
              const labels: Record<string, string> = {
                HOURLY: '每小时',
                DAILY: '每天',
                WEEKLY: '每周',
              };
              return labels[v] || v;
            },
          },
          {
            title: '最低利润率',
            dataIndex: 'min_profit_margin',
            key: 'min_profit_margin',
            render: (v: number) => <Tag color="orange">{v}%</Tag>,
          },
          {
            title: '状态',
            dataIndex: 'enabled',
            key: 'enabled',
            render: (v: boolean) => (
              <Tag color={v ? 'green' : 'default'}>{v ? '启用' : '禁用'}</Tag>
            ),
          },
          {
            title: '操作',
            key: 'action',
            render: (_: any, record: PricingConfig) => (
              <Space>
                <Button
                  type="link"
                  size="small"
                  onClick={() => {
                    setSelectedProduct(record.product_id);
                    form.setFieldsValue(record);
                    setConfigModalVisible(true);
                  }}
                >
                  编辑
                </Button>
                <Button type="link" size="small" onClick={() => message.info('生成定价建议')}>
                  生成建议
                </Button>
              </Space>
            ),
          },
        ]}
      />
    </Card>
  );

  const renderHistory = () => (
    <Card title="定价历史记录">
      <Table
        dataSource={decisions}
        rowKey="id"
        columns={[
          {
            title: '商品名称',
            dataIndex: 'product_name',
            key: 'product_name',
          },
          {
            title: '原价格',
            dataIndex: 'current_price',
            key: 'current_price',
            render: (v: number) => `$${v.toFixed(2)}`,
          },
          {
            title: '调整后价格',
            dataIndex: 'suggested_price',
            key: 'suggested_price',
            render: (v: number) => `$${v.toFixed(2)}`,
          },
          {
            title: '变化幅度',
            dataIndex: 'change_percent',
            key: 'change_percent',
            render: (v: number, record: PricingDecision) => (
              <Tag color={record.adjustment_direction === 'INCREASE' ? 'green' : 'red'}>
                {v > 0 ? '+' : ''}{v.toFixed(1)}%
              </Tag>
            ),
          },
          {
            title: '策略',
            dataIndex: 'strategy_used',
            key: 'strategy_used',
            render: (v: string) => {
              const strategy = strategyOptions.find(s => s.value === v);
              return <Tag>{strategy?.label || v}</Tag>;
            },
          },
          {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            render: (v: string) => {
              const colors: Record<string, string> = {
                PENDING: 'blue',
                EXECUTED: 'green',
                REJECTED: 'red',
                EXPIRED: 'default',
              };
              const labels: Record<string, string> = {
                PENDING: '待审核',
                EXECUTED: '已执行',
                REJECTED: '已拒绝',
                EXPIRED: '已过期',
              };
              return <Tag color={colors[v]}>{labels[v]}</Tag>;
            },
          },
          {
            title: '创建时间',
            dataIndex: 'created_at',
            key: 'created_at',
            render: (v: string) => moment(v).format('YYYY-MM-DD HH:mm'),
          },
          {
            title: '操作',
            key: 'action',
            render: (_: any, record: PricingDecision) => (
              <Button
                type="link"
                size="small"
                onClick={() => {
                  setSelectedDecision(record);
                  setDecisionModalVisible(true);
                }}
              >
                详情
              </Button>
            ),
          },
        ]}
      />
    </Card>
  );

  return (
    <div style={{ padding: 24 }}>
      <Row justify="space-between" align="middle" style={{ marginBottom: 16 }}>
        <Col>
          <Title level={2}>AI动态定价系统</Title>
          <Text type="secondary">智能定价决策、竞品监控与市场分析</Text>
        </Col>
        <Col>
          <Space>
            <Button icon={<SyncOutlined />} onClick={fetchData}>
              刷新数据
            </Button>
            <Button type="primary" icon={<SettingOutlined />}>
              全局设置
            </Button>
          </Space>
        </Col>
      </Row>

      <Spin spinning={loading}>
        <Tabs activeKey={activeTab} onChange={setActiveTab} size="large">
          <TabPane
            tab={
              <span>
                <DollarOutlined />
                总览
              </span>
            }
            key="overview"
          >
            {renderOverview()}
          </TabPane>
          <TabPane
            tab={
              <span>
                <LineChartOutlined />
                竞品监控
              </span>
            }
            key="competitors"
          >
            {renderCompetitors()}
          </TabPane>
          <TabPane
            tab={
              <span>
                <SettingOutlined />
                策略配置
              </span>
            }
            key="configs"
          >
            {renderConfigs()}
          </TabPane>
          <TabPane
            tab={
              <span>
                <BellOutlined />
                价格预警
                <Badge count={alerts.filter(a => !a.is_read).length} style={{ marginLeft: 8 }} />
              </span>
            }
            key="alerts"
          >
            <Card>
              <List
                dataSource={alerts}
                renderItem={item => (
                  <List.Item
                    actions={[
                      !item.is_read && (
                        <Button type="primary" size="small" onClick={() => handleMarkAlertRead(item.id)}>
                          标记已读
                        </Button>
                      ),
                      <Button size="small">查看详情</Button>,
                    ]}
                  >
                    <List.Item.Meta
                      avatar={
                        <Avatar
                          style={{
                            backgroundColor:
                              item.severity === 'CRITICAL'
                                ? '#ff4d4f'
                                : item.severity === 'HIGH'
                                ? '#faad14'
                                : item.severity === 'MEDIUM'
                                ? '#1890ff'
                                : '#52c41a',
                          }}
                          icon={
                            item.alert_type === 'PRICE_DROP' ? (
                              <FallOutlined />
                            ) : item.alert_type === 'PRICE_INCREASE' ? (
                              <RiseOutlined />
                            ) : (
                              <WarningOutlined />
                            )
                          }
                        />
                      }
                      title={
                        <Space>
                          <Text strong={!item.is_read}>{item.competitor_name}</Text>
                          <Tag color={item.severity === 'CRITICAL' ? 'red' : item.severity === 'HIGH' ? 'orange' : 'blue'}>
                            {item.severity}
                          </Tag>
                          <Tag>
                            {item.alert_type === 'PRICE_DROP'
                              ? '降价'
                              : item.alert_type === 'PRICE_INCREASE'
                              ? '涨价'
                              : item.alert_type === 'NEW_COMPETITOR'
                              ? '新竞品'
                              : '库存变化'}
                          </Tag>
                        </Space>
                      }
                      description={
                        <Space direction="vertical">
                          <Text>{item.change_description}</Text>
                          <Text type="secondary">{moment(item.created_at).format('YYYY-MM-DD HH:mm:ss')}</Text>
                        </Space>
                      }
                    />
                  </List.Item>
                )}
              />
            </Card>
          </TabPane>
          <TabPane
            tab={
              <span>
                <LineChartOutlined />
                历史记录
              </span>
            }
            key="history"
          >
            {renderHistory()}
          </TabPane>
        </Tabs>
      </Spin>

      <Modal
        title="定价策略配置"
        visible={configModalVisible}
        onOk={handleSaveConfig}
        onCancel={() => setConfigModalVisible(false)}
        width={600}
      >
        <Form form={form} layout="vertical">
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="base_price" label="基础价格" rules={[{ required: true }]}>
                <InputNumber
                  prefix="$"
                  precision={2}
                  style={{ width: '100%' }}
                  min={0}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="cost_price" label="成本价格" rules={[{ required: true }]}>
                <InputNumber
                  prefix="$"
                  precision={2}
                  style={{ width: '100%' }}
                  min={0}
                />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="min_price" label="最低价格" rules={[{ required: true }]}>
                <InputNumber
                  prefix="$"
                  precision={2}
                  style={{ width: '100%' }}
                  min={0}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="max_price" label="最高价格" rules={[{ required: true }]}>
                <InputNumber
                  prefix="$"
                  precision={2}
                  style={{ width: '100%' }}
                  min={0}
                />
              </Form.Item>
            </Col>
          </Row>
          <Form.Item name="strategy" label="定价策略" rules={[{ required: true }]}>
            <Select>
              {strategyOptions.map(opt => (
                <Option key={opt.value} value={opt.value}>
                  <Tooltip title={opt.desc}>{opt.label}</Tooltip>
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="auto_adjust" label="自动调价" valuePropName="checked">
                <Switch />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="adjust_frequency" label="调价频率">
                <Select>
                  <Option value="HOURLY">每小时</Option>
                  <Option value="DAILY">每天</Option>
                  <Option value="WEEKLY">每周</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="max_adjust_percent" label="最大调整比例 (%)">
                <InputNumber min={1} max={50} style={{ width: '100%' }} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="min_profit_margin" label="最低利润率 (%)">
                <InputNumber min={5} max={100} style={{ width: '100%' }} />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>

      <Modal
        title="定价决策详情"
        visible={decisionModalVisible}
        onCancel={() => setDecisionModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setDecisionModalVisible(false)}>
            关闭
          </Button>,
        ]}
        width={600}
      >
        {selectedDecision && (
          <div>
            <Row gutter={[16, 16]}>
              <Col span={12}>
                <Statistic
                  title="当前价格"
                  value={selectedDecision.current_price}
                  prefix="$"
                  precision={2}
                />
              </Col>
              <Col span={12}>
                <Statistic
                  title="建议价格"
                  value={selectedDecision.suggested_price}
                  prefix="$"
                  precision={2}
                  valueStyle={{
                    color:
                      selectedDecision.adjustment_direction === 'INCREASE'
                        ? '#52c41a'
                        : selectedDecision.adjustment_direction === 'DECREASE'
                        ? '#ff4d4f'
                        : undefined,
                  }}
                />
              </Col>
            </Row>
            <Divider />
            <Title level={5}>预测影响</Title>
            <Row gutter={[16, 16]}>
              <Col span={8}>
                <Statistic
                  title="收益变化"
                  value={selectedDecision.predicted_impact.revenue_change}
                  suffix="%"
                  valueStyle={{
                    color:
                      selectedDecision.predicted_impact.revenue_change > 0 ? '#52c41a' : '#ff4d4f',
                  }}
                />
              </Col>
              <Col span={8}>
                <Statistic
                  title="利润变化"
                  value={selectedDecision.predicted_impact.profit_change}
                  suffix="%"
                  valueStyle={{
                    color:
                      selectedDecision.predicted_impact.profit_change > 0 ? '#52c41a' : '#ff4d4f',
                  }}
                />
              </Col>
              <Col span={8}>
                <Statistic
                  title="销量变化"
                  value={selectedDecision.predicted_impact.sales_change}
                  suffix="%"
                  valueStyle={{
                    color:
                      selectedDecision.predicted_impact.sales_change > 0 ? '#52c41a' : '#ff4d4f',
                  }}
                />
              </Col>
            </Row>
            <Divider />
            <Title level={5}>决策信息</Title>
            <Row gutter={[16, 8]}>
              <Col span={12}>
                <Text type="secondary">策略: </Text>
                <Tag>{strategyOptions.find(s => s.value === selectedDecision.strategy_used)?.label}</Tag>
              </Col>
              <Col span={12}>
                <Text type="secondary">置信度: </Text>
                <Text>{(selectedDecision.predicted_impact.confidence * 100).toFixed(0)}%</Text>
              </Col>
              <Col span={12}>
                <Text type="secondary">创建时间: </Text>
                <Text>{moment(selectedDecision.created_at).format('YYYY-MM-DD HH:mm:ss')}</Text>
              </Col>
              <Col span={12}>
                <Text type="secondary">状态: </Text>
                <Tag color={selectedDecision.status === 'EXECUTED' ? 'green' : 'blue'}>
                  {selectedDecision.status}
                </Tag>
              </Col>
            </Row>
          </div>
        )}
      </Modal>
    </div>
  );
};

export default DynamicPricing;
