import {
  useState,
  useEffect,
  Card,
  Row,
  Col,
  Button,
  Tabs,
  Table,
  DatePicker,
  Select,
  Space,
  Statistic,
  Progress,
  message,
  Modal,
  Form,
  Input,
  Radio,
  Tooltip,
  Badge,
  Dropdown,
  Alert,
  Descriptions,
  Tag,
  Timeline,
  List,
  Avatar,
  Divider,
  Empty,
  Spin,
  Switch,
  Slider,
  Checkbox,
  Collapse,
  Steps,
  Drawer,
  Popover,
  Typography,
  BarChartOutlined,
  LineChartOutlined,
  PieChartOutlined,
  DollarOutlined,
  RiseOutlined,
  FallOutlined,
  DownloadOutlined,
  SearchOutlined,
  FilterOutlined,
  ReloadOutlined,
  FileTextOutlined,
  SettingOutlined,
  ShareAltOutlined,
  CalendarOutlined,
  ShopOutlined,
  ProductOutlined,
  OrderedListOutlined,
  EyeOutlined,
  EditOutlined,
  DeleteOutlined,
  PlusOutlined,
  AreaChartOutlined,
  FundOutlined,
  DashboardOutlined,
  GlobalOutlined,
  TeamOutlined,
  ShoppingCartOutlined,
  InboxOutlined,
  CheckCircleOutlined,
  WarningOutlined,
  InfoCircleOutlined,
  ArrowUpOutlined,
  ArrowDownOutlined,
  MoreOutlined,
  ExportOutlined,
  PrinterOutlined,
  MailOutlined,
  BellOutlined,
  ClockCircleOutlined,
  Line,
  Column,
  Pie,
  Area,
  DualAxes,
  Title,
  Text,
  RangePicker,
  Option,
  Panel,
  Step,
  FC,
} from '@/imports';
import type { ColumnsType } from 'antd/es/table';
import { analyticsDataSource, ProductAnalytics, OrderAnalytics, ProfitAnalytics, RealtimeMetrics, AlertRule, Dashboard } from '@/services/analyticsDataSource';

interface LocalChartData {
  date: string;
  sales: number;
  orders: number;
  visitors: number;
  conversion: number;
}

interface LocalMetricData {
  key: string;
  label: string;
  value: number;
  unit: string;
  change: number;
  changeType: 'up' | 'down' | 'neutral';
  icon: React.ReactNode;
  color: string;
}

const PLATFORM_MAP: Record<string, { color: string; text: string }> = {
  AMAZON: { color: 'orange', text: 'Amazon' },
  EBAY: { color: 'blue', text: 'eBay' },
  SHOPIFY: { color: 'green', text: 'Shopify' },
  SHOPEE: { color: 'red', text: 'Shopee' },
  LAZADA: { color: 'purple', text: 'Lazada' },
};

const ORDER_STATUS_MAP: Record<string, { color: string; text: string }> = {
  PENDING: { color: 'default', text: '待处理' },
  CONFIRMED: { color: 'blue', text: '已确认' },
  SHIPPED: { color: 'processing', text: '已发货' },
  DELIVERED: { color: 'cyan', text: '已送达' },
  COMPLETED: { color: 'success', text: '已完成' },
  CANCELLED: { color: 'error', text: '已取消' },
};

const TREND_MAP: Record<string, { color: string; icon: React.ReactNode }> = {
  up: { color: '#52c41a', icon: <RiseOutlined /> },
  down: { color: '#ff4d4f', icon: <FallOutlined /> },
  stable: { color: '#faad14', icon: <LineChartOutlined /> },
};

const SALES_TREND_DATA = [
  { date: '2026-03-01', sales: 45000, orders: 120, visitors: 3500 },
  { date: '2026-03-02', sales: 52000, orders: 145, visitors: 4200 },
  { date: '2026-03-03', sales: 48000, orders: 132, visitors: 3800 },
  { date: '2026-03-04', sales: 61000, orders: 168, visitors: 4800 },
  { date: '2026-03-05', sales: 55000, orders: 152, visitors: 4100 },
  { date: '2026-03-06', sales: 67000, orders: 185, visitors: 5200 },
  { date: '2026-03-07', sales: 72000, orders: 198, visitors: 5800 },
  { date: '2026-03-08', sales: 68000, orders: 187, visitors: 5100 },
  { date: '2026-03-09', sales: 75000, orders: 205, visitors: 6000 },
  { date: '2026-03-10', sales: 82000, orders: 225, visitors: 6500 },
];

const PLATFORM_REVENUE_DATA = [
  { platform: 'Amazon', revenue: 125000, orders: 450, growth: 15.2 },
  { platform: 'eBay', revenue: 89000, orders: 320, growth: 8.5 },
  { platform: 'Shopify', revenue: 71000, orders: 280, growth: 22.3 },
  { platform: 'Shopee', revenue: 53000, orders: 190, growth: 35.1 },
  { platform: 'Lazada', revenue: 28000, orders: 95, growth: 12.8 },
];

const CATEGORY_DATA = [
  { category: '电子产品', sales: 180000, percentage: 35 },
  { category: '服装', sales: 120000, percentage: 23 },
  { category: '家居', sales: 95000, percentage: 18 },
  { category: '美妆', sales: 75000, percentage: 14 },
  { category: '运动', sales: 52000, percentage: 10 },
];

const HOURLY_TRAFFIC_DATA = [
  { hour: '00:00', visitors: 120, orders: 3 },
  { hour: '02:00', visitors: 80, orders: 2 },
  { hour: '04:00', visitors: 50, orders: 1 },
  { hour: '06:00', visitors: 90, orders: 4 },
  { hour: '08:00', visitors: 250, orders: 12 },
  { hour: '10:00', visitors: 420, orders: 25 },
  { hour: '12:00', visitors: 580, orders: 35 },
  { hour: '14:00', visitors: 520, orders: 30 },
  { hour: '16:00', visitors: 480, orders: 28 },
  { hour: '18:00', visitors: 650, orders: 42 },
  { hour: '20:00', visitors: 720, orders: 48 },
  { hour: '22:00', visitors: 380, orders: 22 },
];

const Analytics: FC = () => {
  const [loading, setLoading] = useState(false);
  const [activeTab, setActiveTab] = useState('overview');
  const [dateRange, setDateRange] = useState<[string, string] | null>(null);
  const [selectedShop, setSelectedShop] = useState<string>('');
  const [selectedPlatform, setSelectedPlatform] = useState<string>('');
  
  const userRole = 'OPERATOR';
  
  const roleTabPermissions: Record<string, string[]> = {
    ADMIN: ['overview', 'products', 'orders', 'profit', 'alerts'],
    MANAGER: ['overview', 'products', 'orders', 'profit'],
    OPERATOR: ['overview', 'products', 'orders'],
  };
  
  const accessibleTabs = roleTabPermissions[userRole] || ['overview'];
  
  const [metrics, setMetrics] = useState<LocalMetricData[]>([]);
  const [chartData, setChartData] = useState<LocalChartData[]>([]);
  const [productAnalytics, setProductAnalytics] = useState<ProductAnalytics[]>([]);
  const [orderAnalytics, setOrderAnalytics] = useState<OrderAnalytics[]>([]);
  const [profitAnalytics, setProfitAnalytics] = useState<ProfitAnalytics[]>([]);
  const [realtimeMetrics, setRealtimeMetrics] = useState<RealtimeMetrics[]>([]);
  const [alertRules, setAlertRules] = useState<AlertRule[]>([]);
  const [dashboards, setDashboards] = useState<Dashboard[]>([]);
  
  const [alertModalVisible, setAlertModalVisible] = useState(false);
  const [dashboardModalVisible, setDashboardModalVisible] = useState(false);
  const [exportModalVisible, setExportModalVisible] = useState(false);
  const [detailDrawerVisible, setDetailDrawerVisible] = useState(false);
  const [selectedItem, setSelectedItem] = useState<Record<string, unknown> | null>(null);
  
  const [alertForm] = Form.useForm();
  const [dashboardForm] = Form.useForm();

  useEffect(() => {
    fetchAllData();
    const interval = setInterval(fetchRealtimeData, 30000);
    return () => clearInterval(interval);
  }, []);

  const iconMap: Record<string, React.ReactNode> = {
    DollarOutlined: <DollarOutlined />,
    ShoppingCartOutlined: <ShoppingCartOutlined />,
    TeamOutlined: <TeamOutlined />,
    FundOutlined: <FundOutlined />,
    BarChartOutlined: <BarChartOutlined />,
    LineChartOutlined: <LineChartOutlined />,
  };

  const fetchAllData = async () => {
    setLoading(true);
    try {
      const data = await analyticsDataSource.fetchAllData();
      const localMetrics: LocalMetricData[] = data.metrics.map(m => ({
        ...m,
        icon: iconMap[m.icon] || <BarChartOutlined />,
      }));
      setMetrics(localMetrics);
      setChartData(data.chartData);
      setProductAnalytics(data.productAnalytics);
      setOrderAnalytics(data.orderAnalytics);
      setProfitAnalytics(data.profitAnalytics);
      setRealtimeMetrics(data.realtimeMetrics);
      setAlertRules(data.alertRules);
      setDashboards(data.dashboards);
    } catch (error) {
      message.error('加载数据失败');
    } finally {
      setLoading(false);
    }
  };

  const fetchRealtimeData = async () => {
    try {
      const data = await analyticsDataSource.fetchRealtimeData();
      setRealtimeMetrics(data);
    } catch (error) {
      console.error('加载实时数据失败', error);
    }
  };

  const fetchAlertRules = async () => {
    try {
      const data = await analyticsDataSource.fetchAlertRules();
      setAlertRules(data);
    } catch (error) {
      message.error('加载告警规则失败');
    }
  };

  const handleRefresh = () => {
    fetchAllData();
    message.success('数据已刷新');
  };

  const handleExport = () => {
    setExportModalVisible(true);
  };

  const handleCreateAlert = () => {
    alertForm.resetFields();
    setAlertModalVisible(true);
  };

  const handleSaveAlert = async () => {
    try {
      const values = await alertForm.validateFields();
      console.log('Creating alert rule:', values);
      message.success('告警规则已创建');
      setAlertModalVisible(false);
      fetchAlertRules();
    } catch (error) {
      message.error('创建失败');
    }
  };

  const handleToggleAlert = (id: string, enabled: boolean) => {
    setAlertRules(prev => prev.map(rule => 
      rule.id === id ? { ...rule, enabled } : rule
    ));
    message.success(`告警规则已${enabled ? '启用' : '禁用'}`);
  };

  const handleDeleteAlert = (id: string) => {
    setAlertRules(prev => prev.filter(rule => rule.id !== id));
    message.success('告警规则已删除');
  };

  const handleViewDetail = (item: unknown, type: string) => {
    setSelectedItem({ ...(item as object), type });
    setDetailDrawerVisible(true);
  };

  const productColumns: ColumnsType<ProductAnalytics> = [
    {
      title: '商品信息',
      dataIndex: 'name',
      key: 'name',
      render: (text, record) => (
        <Space>
          <Avatar src={record.image} shape="square" size={48} />
          <div>
            <div style={{ fontWeight: 500 }}>{text}</div>
            <div style={{ fontSize: 12, color: '#999' }}>{record.productId}</div>
            <Tag style={{ fontSize: 11 }}>{record.category}</Tag>
          </div>
        </Space>
      ),
    },
    { title: '销量', dataIndex: 'sales', key: 'sales', sorter: (a, b) => a.sales - b.sales },
    { title: '销售额', dataIndex: 'revenue', key: 'revenue', render: (v) => `¥${v.toLocaleString()}`, sorter: (a, b) => a.revenue - b.revenue },
    { title: '利润', dataIndex: 'profit', key: 'profit', render: (v) => `¥${v.toLocaleString()}`, sorter: (a, b) => a.profit - b.profit },
    { title: '利润率', dataIndex: 'profitMargin', key: 'profitMargin', render: (v) => `${v}%`, sorter: (a, b) => a.profitMargin - b.profitMargin },
    { title: '浏览量', dataIndex: 'views', key: 'views', sorter: (a, b) => a.views - b.views },
    { title: '转化率', dataIndex: 'conversionRate', key: 'conversionRate', render: (v) => `${v}%`, sorter: (a, b) => a.conversionRate - b.conversionRate },
    { title: '退货率', dataIndex: 'returnRate', key: 'returnRate', render: (v) => <Tag color={v > 5 ? 'error' : 'success'}>{v}%</Tag>, sorter: (a, b) => a.returnRate - b.returnRate },
    {
      title: '趋势',
      dataIndex: 'trend',
      key: 'trend',
      render: (trend) => (
        <Tag icon={TREND_MAP[trend].icon} color={TREND_MAP[trend].color}>
          {trend === 'up' ? '上升' : trend === 'down' ? '下降' : '平稳'}
        </Tag>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Button type="link" icon={<EyeOutlined />} onClick={() => handleViewDetail(record, 'product')}>
          详情
        </Button>
      ),
    },
  ];

  const orderColumns: ColumnsType<OrderAnalytics> = [
    { title: '订单号', dataIndex: 'orderId', key: 'orderId' },
    { title: '平台', dataIndex: 'platform', key: 'platform', render: (p) => <Tag color={PLATFORM_MAP[p]?.color}>{PLATFORM_MAP[p]?.text}</Tag> },
    { title: '状态', dataIndex: 'status', key: 'status', render: (s) => <Tag color={ORDER_STATUS_MAP[s]?.color}>{ORDER_STATUS_MAP[s]?.text}</Tag> },
    { title: '金额', dataIndex: 'amount', key: 'amount', render: (v) => `¥${v.toFixed(2)}` },
    { title: '利润', dataIndex: 'profit', key: 'profit', render: (v) => `¥${v.toFixed(2)}` },
    { title: '客户类型', dataIndex: 'customerType', key: 'customerType', render: (t) => <Tag color={t === 'new' ? 'blue' : 'green'}>{t === 'new' ? '新客户' : '回头客'}</Tag> },
    { title: '物流成本', dataIndex: 'shippingCost', key: 'shippingCost', render: (v) => `¥${v.toFixed(2)}` },
    { title: '平台费用', dataIndex: 'platformFee', key: 'platformFee', render: (v) => `¥${v.toFixed(2)}` },
    { title: '创建时间', dataIndex: 'createdAt', key: 'createdAt' },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Button type="link" icon={<EyeOutlined />} onClick={() => handleViewDetail(record, 'order')}>
          详情
        </Button>
      ),
    },
  ];

  const profitColumns: ColumnsType<ProfitAnalytics> = [
    { title: '日期', dataIndex: 'period', key: 'period' },
    { title: '收入', dataIndex: 'revenue', key: 'revenue', render: (v) => `¥${v.toLocaleString()}` },
    { title: '成本', dataIndex: 'cost', key: 'cost', render: (v) => `¥${v.toLocaleString()}` },
    { title: '毛利润', dataIndex: 'grossProfit', key: 'grossProfit', render: (v) => `¥${v.toLocaleString()}` },
    { title: '净利润', dataIndex: 'netProfit', key: 'netProfit', render: (v) => <span style={{ color: '#52c41a', fontWeight: 500 }}>¥{v.toLocaleString()}</span> },
    { title: '利润率', dataIndex: 'margin', key: 'margin', render: (v) => `${v}%` },
    { title: '平台费', dataIndex: 'platformFees', key: 'platformFees', render: (v) => `¥${v.toLocaleString()}` },
    { title: '物流费', dataIndex: 'shippingCost', key: 'shippingCost', render: (v) => `¥${v.toLocaleString()}` },
    { title: '广告费', dataIndex: 'adSpend', key: 'adSpend', render: (v) => `¥${v.toLocaleString()}` },
  ];

  const alertColumns: ColumnsType<AlertRule> = [
    { title: '规则名称', dataIndex: 'name', key: 'name' },
    { title: '指标', dataIndex: 'metric', key: 'metric' },
    { title: '条件', dataIndex: 'condition', key: 'condition', render: (c) => `${c}` },
    { title: '阈值', dataIndex: 'threshold', key: 'threshold' },
    { title: '通知渠道', dataIndex: 'notifyChannels', key: 'notifyChannels', render: (channels) => channels?.map((c: string) => <Tag key={c}>{c}</Tag>) || '-', },
    { title: '最后触发', dataIndex: 'lastTriggered', key: 'lastTriggered', render: (v) => v || '-' },
    {
      title: '状态',
      dataIndex: 'enabled',
      key: 'enabled',
      render: (enabled, record) => (
        <Switch checked={enabled} onChange={(checked) => handleToggleAlert(record.id, checked)} />
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space>
          <Button type="link" icon={<EditOutlined />}>编辑</Button>
          <Button type="link" danger icon={<DeleteOutlined />} onClick={() => handleDeleteAlert(record.id)}>删除</Button>
        </Space>
      ),
    },
  ];

  const salesTrendConfig = {
    data: SALES_TREND_DATA.flatMap(item => [
      { date: item.date, value: item.sales, type: '销售额' },
      { date: item.date, value: item.orders * 100, type: '订单数' },
    ]),
    xField: 'date',
    yField: 'value',
    seriesField: 'type',
    smooth: true,
    legend: { position: 'top' as const },
    yAxis: { label: { formatter: (v: number) => `¥${v / 1000}k` } },
  };

  const platformRevenueConfig = {
    data: PLATFORM_REVENUE_DATA,
    xField: 'platform',
    yField: 'revenue',
    color: '#1890ff',
    label: { text: 'revenue', position: 'top' as const },
  };

  const categoryPieConfig = {
    data: CATEGORY_DATA,
    angleField: 'percentage',
    colorField: 'category',
    radius: 0.8,
    innerRadius: 0.6,
    label: { text: 'category', position: 'outside' },
    legend: { position: 'bottom' as const },
  };

  const hourlyTrafficConfig = {
    data: [HOURLY_TRAFFIC_DATA, HOURLY_TRAFFIC_DATA],
    xField: 'hour',
    yField: ['visitors', 'orders'],
    geometryOptions: [
      { geometry: 'line', color: '#1890ff' },
      { geometry: 'line', color: '#52c41a' },
    ],
    legend: { position: 'top' as const },
  };

  const tabItems = [
    ...(accessibleTabs.includes('overview') ? [{
      key: 'overview',
      label: <span><DashboardOutlined />数据概览</span>,
      children: (
        <Spin spinning={loading}>
          <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
            {metrics.map(metric => (
              <Col xs={12} sm={6} lg={4} key={metric.key}>
                <Card hoverable size="small">
                  <Statistic
                    title={metric.label}
                    value={metric.value}
                    prefix={metric.icon}
                    suffix={metric.unit}
                    valueStyle={{ color: metric.color, fontSize: 18 }}
                  />
                  <div style={{ marginTop: 8 }}>
                    {metric.changeType === 'up' ? (
                      <span style={{ color: '#52c41a' }}><ArrowUpOutlined /> {metric.change}%</span>
                    ) : metric.changeType === 'down' ? (
                      <span style={{ color: '#ff4d4f' }}><ArrowDownOutlined /> {Math.abs(metric.change)}%</span>
                    ) : (
                      <span style={{ color: '#faad14' }}>-</span>
                    )}
                    <span style={{ color: '#999', marginLeft: 8 }}>环比</span>
                  </div>
                </Card>
              </Col>
            ))}
          </Row>

          <Card title="实时监控" style={{ marginBottom: 24 }} size="small">
            <Row gutter={16}>
              <Col span={6}>
                <Statistic title="当前在线用户" value={realtimeMetrics[0]?.activeUsers || 1250} prefix={<TeamOutlined />} valueStyle={{ color: '#1890ff' }} />
              </Col>
              <Col span={6}>
                <Statistic title="每分钟订单" value={realtimeMetrics[0]?.ordersPerMinute || 8} prefix={<ShoppingCartOutlined />} valueStyle={{ color: '#52c41a' }} />
              </Col>
              <Col span={6}>
                <Statistic title="每分钟收入" value={realtimeMetrics[0]?.revenuePerMinute || 1250} prefix={<DollarOutlined />} suffix="¥" valueStyle={{ color: '#fa8c16' }} />
              </Col>
              <Col span={6}>
                <Statistic title="实时转化率" value={realtimeMetrics[0]?.conversionRate || 4.2} prefix={<FundOutlined />} suffix="%" valueStyle={{ color: '#722ed1' }} />
              </Col>
            </Row>
          </Card>

          <Row gutter={16}>
            <Col xs={24} lg={16}>
              <Card title="销售趋势" extra={<RangePicker />}>
                <Line {...salesTrendConfig} height={280} />
              </Card>
            </Col>
            <Col xs={24} lg={8}>
              <Card title="品类占比">
                <Pie {...categoryPieConfig} height={280} />
              </Card>
            </Col>
          </Row>

          <Row gutter={16} style={{ marginTop: 16 }}>
            <Col xs={24} lg={12}>
              <Card title="平台收入对比">
                <Column {...platformRevenueConfig} height={250} />
              </Card>
            </Col>
            <Col xs={24} lg={12}>
              <Card title="流量时段分布">
                <DualAxes {...hourlyTrafficConfig} height={250} />
              </Card>
            </Col>
          </Row>
        </Spin>
      ),
    }] : []),
    ...(accessibleTabs.includes('products') ? [{
      key: 'products',
      label: <span><ProductOutlined />商品分析</span>,
      children: (
        <Card>
          <Row justify="space-between" style={{ marginBottom: 16 }}>
            <Col>
              <Space>
                <Input.Search placeholder="搜索商品" style={{ width: 200 }} />
                <Select defaultValue="all" style={{ width: 120 }}>
                  <Option value="all">全部品类</Option>
                  <Option value="electronics">电子产品</Option>
                  <Option value="clothing">服装</Option>
                  <Option value="home">家居</Option>
                </Select>
              </Space>
            </Col>
            <Col>
              <Space>
                <Button icon={<ReloadOutlined />}>刷新</Button>
                <Button icon={<ExportOutlined />}>导出</Button>
              </Space>
            </Col>
          </Row>
          <Table columns={productColumns} dataSource={productAnalytics} rowKey="productId" pagination={{ pageSize: 10 }} loading={loading} scroll={{ x: 1200 }} />
        </Card>
      ),
    }] : []),
    ...(accessibleTabs.includes('orders') ? [{
      key: 'orders',
      label: <span><OrderedListOutlined />订单分析</span>,
      children: (
        <Card>
          <Row justify="space-between" style={{ marginBottom: 16 }}>
            <Col>
              <Space>
                <Input.Search placeholder="搜索订单" style={{ width: 200 }} />
                <Select defaultValue="all" style={{ width: 120 }}>
                  <Option value="all">全部平台</Option>
                  {Object.keys(PLATFORM_MAP).map(key => (
                    <Option key={key} value={key}>{PLATFORM_MAP[key].text}</Option>
                  ))}
                </Select>
                <Select defaultValue="all" style={{ width: 120 }}>
                  <Option value="all">全部状态</Option>
                  {Object.keys(ORDER_STATUS_MAP).map(key => (
                    <Option key={key} value={key}>{ORDER_STATUS_MAP[key].text}</Option>
                  ))}
                </Select>
              </Space>
            </Col>
            <Col>
              <Space>
                <Button icon={<ReloadOutlined />}>刷新</Button>
                <Button icon={<ExportOutlined />}>导出</Button>
              </Space>
            </Col>
          </Row>
          <Table columns={orderColumns} dataSource={orderAnalytics} rowKey="orderId" pagination={{ pageSize: 10 }} loading={loading} scroll={{ x: 1200 }} />
        </Card>
      ),
    }] : []),
    ...(accessibleTabs.includes('profit') ? [{
      key: 'profit',
      label: <span><FundOutlined />利润分析</span>,
      children: (
        <Card>
          <Row justify="space-between" style={{ marginBottom: 16 }}>
            <Col>
              <RangePicker />
            </Col>
            <Col>
              <Space>
                <Button icon={<ReloadOutlined />}>刷新</Button>
                <Button icon={<ExportOutlined />}>导出</Button>
              </Space>
            </Col>
          </Row>
          <Table columns={profitColumns} dataSource={profitAnalytics} rowKey="period" pagination={{ pageSize: 10 }} loading={loading} scroll={{ x: 1000 }} />
        </Card>
      ),
    }] : []),
    ...(accessibleTabs.includes('alerts') ? [{
      key: 'alerts',
      label: <span><BellOutlined />告警规则</span>,
      children: (
        <Card>
          <Row justify="space-between" style={{ marginBottom: 16 }}>
            <Col>
              <Title level={5}>告警规则管理</Title>
            </Col>
            <Col>
              <Button type="primary" icon={<PlusOutlined />} onClick={handleCreateAlert}>新建规则</Button>
            </Col>
          </Row>
          <Table columns={alertColumns} dataSource={alertRules} rowKey="id" pagination={{ pageSize: 10 }} loading={loading} />
        </Card>
      ),
    }] : []),
  ];

  return (
    <div className="analytics-page" style={{ padding: 24 }}>
      <Card
        title={<Space><BarChartOutlined /> 数据中心</Space>}
        extra={
          <Space>
            <Select placeholder="选择店铺" value={selectedShop} onChange={setSelectedShop} allowClear style={{ width: 150 }}>
              <Option value="shop1">Amazon US Store</Option>
              <Option value="shop2">eBay Outlet</Option>
              <Option value="shop3">Shopify Brand</Option>
            </Select>
            <Select placeholder="选择平台" value={selectedPlatform} onChange={setSelectedPlatform} allowClear style={{ width: 120 }}>
              {Object.keys(PLATFORM_MAP).map(key => (
                <Option key={key} value={key}>{PLATFORM_MAP[key].text}</Option>
              ))}
            </Select>
            <RangePicker onChange={(dates) => setDateRange(dates ? [dates[0]?.format('YYYY-MM-DD') || '', dates[1]?.format('YYYY-MM-DD') || ''] : null)} />
            <Button icon={<ReloadOutlined />} onClick={handleRefresh}>刷新</Button>
            <Button type="primary" icon={<DownloadOutlined />} onClick={handleExport}>导出</Button>
          </Space>
        }
      >
        <Tabs activeKey={activeTab} onChange={setActiveTab} items={tabItems} />
      </Card>

      <Modal
        title="新建告警规则"
        open={alertModalVisible}
        onOk={handleSaveAlert}
        onCancel={() => setAlertModalVisible(false)}
        width={600}
      >
        <Form form={alertForm} layout="vertical">
          <Form.Item name="name" label="规则名称" rules={[{ required: true }]}>
            <Input placeholder="请输入规则名称" />
          </Form.Item>
          <Form.Item name="metric" label="监控指标" rules={[{ required: true }]}>
            <Select placeholder="选择监控指标">
              <Option value="sales">销售额</Option>
              <Option value="orders">订单数</Option>
              <Option value="profit">利润率</Option>
              <Option value="conversion">转化率</Option>
            </Select>
          </Form.Item>
          <Form.Item name="condition" label="触发条件" rules={[{ required: true }]}>
            <Select placeholder="选择条件">
              <Option value="gt">大于</Option>
              <Option value="lt">小于</Option>
              <Option value="eq">等于</Option>
            </Select>
          </Form.Item>
          <Form.Item name="threshold" label="阈值" rules={[{ required: true }]}>
            <Input type="number" placeholder="请输入阈值" />
          </Form.Item>
          <Form.Item name="notifyChannels" label="通知渠道" rules={[{ required: true }]}>
            <Checkbox.Group>
              <Checkbox value="email">邮件</Checkbox>
              <Checkbox value="sms">短信</Checkbox>
              <Checkbox value="wechat">微信</Checkbox>
            </Checkbox.Group>
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="导出数据"
        open={exportModalVisible}
        onCancel={() => setExportModalVisible(false)}
        footer={[
          <Button key="cancel" onClick={() => setExportModalVisible(false)}>取消</Button>,
          <Button key="export" type="primary" icon={<ExportOutlined />}>导出</Button>,
        ]}
      >
        <Form layout="vertical">
          <Form.Item label="导出格式">
            <Radio.Group defaultValue="excel">
              <Radio value="excel">Excel</Radio>
              <Radio value="csv">CSV</Radio>
              <Radio value="pdf">PDF</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item label="导出范围">
            <Checkbox.Group defaultValue={['overview', 'products', 'orders']}>
              <Checkbox value="overview">数据概览</Checkbox>
              <Checkbox value="products">商品分析</Checkbox>
              <Checkbox value="orders">订单分析</Checkbox>
              <Checkbox value="profit">利润分析</Checkbox>
            </Checkbox.Group>
          </Form.Item>
        </Form>
      </Modal>

      <Drawer
        title="详情"
        placement="right"
        width={600}
        onClose={() => setDetailDrawerVisible(false)}
        open={detailDrawerVisible}
      >
        {selectedItem && (
          <Descriptions column={1} bordered>
            {Object.entries(selectedItem).map(([key, value]) => (
              <Descriptions.Item key={key} label={key}>
                {typeof value === 'object' ? JSON.stringify(value) : String(value)}
              </Descriptions.Item>
            ))}
          </Descriptions>
        )}
      </Drawer>
    </div>
  );
};

export default Analytics;
