import {
  useState,
  useMemo,
  Card,
  Row,
  Col,
  Statistic,
  Button,
  Tabs,
  Table,
  Tag,
  Select,
  DatePicker,
  Space,
  Typography,
  Progress,
  Alert,
  Drawer,
  Descriptions,
  Tooltip,
  Rate,
  BarChartOutlined,
  LineChartOutlined,
  RiseOutlined,
  UserOutlined,
  DollarOutlined,
  EyeOutlined,
  ShoppingCartOutlined,
  ExportOutlined,
  ReloadOutlined,
  TrophyOutlined,
  StarOutlined,
  ThunderboltOutlined,
  FireOutlined,
  ArrowUpOutlined,
  ArrowDownOutlined,
  WarningOutlined,
  useNavigate,
  LineChart,
  BarChart,
  Line,
  Bar,
  Pie,
  ResponsiveContainer,
  Legend,
  XAxis,
  YAxis,
  CartesianGrid,
  Cell,
  Radar,
  RadarChart,
  PolarGrid,
  PolarAngleAxis,
  PolarRadiusAxis,
  Title,
  Text,
  RangePicker,
  Option,
  FC,
} from '@/imports';
import type { ColumnsType } from 'antd/es/table';
import moment from 'moment';

interface AdCampaign {
  id: string;
  name: string;
  platform: string;
  status: 'active' | 'paused' | 'completed';
  budget: number;
  spent: number;
  impressions: number;
  clicks: number;
  conversions: number;
  ctr: number;
  roas: number;
  startDate: string;
  endDate?: string;
}

interface AdPerformance {
  date: string;
  impressions: number;
  clicks: number;
  conversions: number;
  spend: number;
  revenue: number;
}

interface CompetitorData {
  id: string;
  name: string;
  platform: string;
  adSpend: number;
  marketShare: number;
  avgPrice: number;
  productCount: number;
  rating: number;
}

const MOCK_CAMPAIGNS: AdCampaign[] = [
  { id: '1', name: 'Amazon PPC - 核心关键词', platform: 'Amazon', status: 'active', budget: 5000, spent: 3250, impressions: 520000, clicks: 15600, conversions: 468, ctr: 3.0, roas: 4.2, startDate: '2026-03-01', endDate: '2026-03-31' },
  { id: '2', name: 'eBay 促销推广', platform: 'eBay', status: 'active', budget: 3000, spent: 2100, impressions: 280000, clicks: 8400, conversions: 252, ctr: 3.0, roas: 3.8, startDate: '2026-03-05' },
  { id: '3', name: 'Shopify 社交媒体广告', platform: 'Shopify', status: 'paused', budget: 2000, spent: 1200, impressions: 180000, clicks: 5400, conversions: 108, ctr: 3.0, roas: 2.9, startDate: '2026-03-10' },
  { id: '4', name: 'Shopee 直播推广', platform: 'Shopee', status: 'active', budget: 1500, spent: 980, impressions: 150000, clicks: 6000, conversions: 180, ctr: 4.0, roas: 5.1, startDate: '2026-03-12' },
  { id: '5', name: 'Google Shopping', platform: 'Google', status: 'completed', budget: 4000, spent: 4000, impressions: 420000, clicks: 12600, conversions: 378, ctr: 3.0, roas: 3.5, startDate: '2026-02-01', endDate: '2026-02-28' },
];

const PERFORMANCE_DATA: AdPerformance[] = [
  { date: '2026-03-12', impressions: 45000, clicks: 1350, conversions: 40, spend: 1200, revenue: 4800 },
  { date: '2026-03-13', impressions: 52000, clicks: 1560, conversions: 46, spend: 1400, revenue: 5600 },
  { date: '2026-03-14', impressions: 48000, clicks: 1440, conversions: 43, spend: 1300, revenue: 5200 },
  { date: '2026-03-15', impressions: 61000, clicks: 1830, conversions: 54, spend: 1600, revenue: 6400 },
  { date: '2026-03-16', impressions: 55000, clicks: 1650, conversions: 49, spend: 1500, revenue: 6000 },
  { date: '2026-03-17', impressions: 67000, clicks: 2010, conversions: 60, spend: 1800, revenue: 7200 },
  { date: '2026-03-18', impressions: 72000, clicks: 2160, conversions: 64, spend: 1900, revenue: 7600 },
];

const COMPETITOR_DATA: CompetitorData[] = [
  { id: '1', name: 'Competitor A', platform: 'Amazon', adSpend: 15000, marketShare: 25, avgPrice: 89.99, productCount: 120, rating: 4.2 },
  { id: '2', name: 'Competitor B', platform: 'Amazon', adSpend: 12000, marketShare: 20, avgPrice: 95.99, productCount: 95, rating: 4.0 },
  { id: '3', name: 'Competitor C', platform: 'eBay', adSpend: 8000, marketShare: 15, avgPrice: 79.99, productCount: 80, rating: 4.5 },
  { id: '4', name: 'Competitor D', platform: 'Shopify', adSpend: 10000, marketShare: 18, avgPrice: 109.99, productCount: 70, rating: 4.3 },
  { id: '5', name: 'Competitor E', platform: 'Shopee', adSpend: 6000, marketShare: 12, avgPrice: 69.99, productCount: 60, rating: 4.1 },
];

const Marketing: FC = () => {
  const navigate = useNavigate();
  const [activeTab, setActiveTab] = useState('overview');
  const [loading, setLoading] = useState(false);
  const [campaigns] = useState<AdCampaign[]>(MOCK_CAMPAIGNS);
  const [competitors] = useState<CompetitorData[]>(COMPETITOR_DATA);
  const [selectedCampaign, setSelectedCampaign] = useState<AdCampaign | null>(null);
  const [detailDrawerVisible, setDetailDrawerVisible] = useState(false);

  const statusColors: Record<string, string> = {
    active: 'success',
    paused: 'warning',
    completed: 'default',
  };

  const statusTexts: Record<string, string> = {
    active: '投放中',
    paused: '已暂停',
    completed: '已结束',
  };

  const campaignColumns: ColumnsType<AdCampaign> = [
    {
      title: '广告系列',
      dataIndex: 'name',
      key: 'name',
      render: (text) => <Text strong>{text}</Text>,
    },
    {
      title: '平台',
      dataIndex: 'platform',
      key: 'platform',
      render: (platform) => <Tag color="blue">{platform}</Tag>,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => <Tag color={statusColors[status]}>{statusTexts[status]}</Tag>,
    },
    {
      title: '预算',
      dataIndex: 'budget',
      key: 'budget',
      render: (budget, record) => (
        <div>
          <div>${budget.toLocaleString()}</div>
          <Text type="secondary" style={{ fontSize: 12 }}>已花费: ${record.spent.toLocaleString()}</Text>
          <Progress percent={Math.round((record.spent / budget) * 100)} size="small" showInfo={false} />
        </div>
      ),
    },
    {
      title: '展示',
      dataIndex: 'impressions',
      key: 'impressions',
      render: (val) => val.toLocaleString(),
    },
    {
      title: '点击',
      dataIndex: 'clicks',
      key: 'clicks',
      render: (val) => val.toLocaleString(),
    },
    {
      title: 'CTR',
      dataIndex: 'ctr',
      key: 'ctr',
      render: (val) => `${val}%`,
    },
    {
      title: '转化',
      dataIndex: 'conversions',
      key: 'conversions',
      render: (val) => val.toLocaleString(),
    },
    {
      title: 'ROAS',
      dataIndex: 'roas',
      key: 'roas',
      render: (val) => (
        <Text style={{ color: val >= 3 ? '#52c41a' : val >= 2 ? '#faad14' : '#ff4d4f' }}>
          {val}x
        </Text>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: AdCampaign) => (
        <Button type="link" size="small" onClick={() => {
          setSelectedCampaign(record);
          setDetailDrawerVisible(true);
        }}>
          查看详情
        </Button>
      ),
    },
  ];

  const competitorColumns: ColumnsType<CompetitorData> = [
    {
      title: '竞争对手',
      dataIndex: 'name',
      key: 'name',
      render: (text) => <Text strong>{text}</Text>,
    },
    {
      title: '平台',
      dataIndex: 'platform',
      key: 'platform',
      render: (platform) => <Tag color="blue">{platform}</Tag>,
    },
    {
      title: '广告支出',
      dataIndex: 'adSpend',
      key: 'adSpend',
      render: (val) => `$${val.toLocaleString()}`,
      sorter: (a: CompetitorData, b: CompetitorData) => a.adSpend - b.adSpend,
    },
    {
      title: '市场份额',
      dataIndex: 'marketShare',
      key: 'marketShare',
      render: (val) => `${val}%`,
      sorter: (a: CompetitorData, b: CompetitorData) => a.marketShare - b.marketShare,
    },
    {
      title: '平均价格',
      dataIndex: 'avgPrice',
      key: 'avgPrice',
      render: (val) => `$${val.toFixed(2)}`,
      sorter: (a: CompetitorData, b: CompetitorData) => a.avgPrice - b.avgPrice,
    },
    {
      title: '商品数量',
      dataIndex: 'productCount',
      key: 'productCount',
      render: (val) => val.toLocaleString(),
      sorter: (a: CompetitorData, b: CompetitorData) => a.productCount - b.productCount,
    },
    {
      title: '评分',
      dataIndex: 'rating',
      key: 'rating',
      render: (val) => <Rate disabled defaultValue={val} style={{ fontSize: 14 }} />,
      sorter: (a: CompetitorData, b: CompetitorData) => a.rating - b.rating,
    },
  ];

  const stats = useMemo(() => {
    const activeCampaigns = campaigns.filter(c => c.status === 'active');
    const totalImpressions = campaigns.reduce((sum, c) => sum + c.impressions, 0);
    const totalClicks = campaigns.reduce((sum, c) => sum + c.clicks, 0);
    const totalConversions = campaigns.reduce((sum, c) => sum + c.conversions, 0);
    const totalSpend = campaigns.reduce((sum, c) => sum + c.spent, 0);
    const totalRevenue = totalSpend * 3.8;
    const avgCTR = totalClicks > 0 ? (totalClicks / totalImpressions) * 100 : 0;
    const avgROAS = totalSpend > 0 ? totalRevenue / totalSpend : 0;
    
    return {
      totalSpend,
      totalRevenue,
      totalImpressions,
      totalClicks,
      totalConversions,
      avgCTR,
      avgROAS,
      activeCampaigns: activeCampaigns.length,
    };
  }, [campaigns]);

  const platformData = useMemo(() => {
    const platformMap: Record<string, { spend: number; revenue: number; conversions: number }> = {};
    campaigns.forEach(c => {
      if (!platformMap[c.platform]) {
        platformMap[c.platform] = { spend: 0, revenue: 0, conversions: 0 };
      }
      platformMap[c.platform].spend += c.spent;
      platformMap[c.platform].revenue += c.spent * c.roas;
      platformMap[c.platform].conversions += c.conversions;
    });
    return Object.entries(platformMap).map(([platform, data]) => ({
      platform,
      ...data,
      roas: data.spend > 0 ? data.revenue / data.spend : 0,
    }));
  }, [campaigns]);

  const trendData = useMemo(() => {
    return PERFORMANCE_DATA.map(item => ({
      date: moment(item.date).format('MM-DD'),
      spend: item.spend,
      revenue: item.revenue,
      conversions: item.conversions,
    }));
  }, []);

  const competitorRadarData = useMemo(() => {
    const maxValues = {
      adSpend: Math.max(...competitors.map(c => c.adSpend)),
      marketShare: Math.max(...competitors.map(c => c.marketShare)),
      productCount: Math.max(...competitors.map(c => c.productCount)),
      rating: Math.max(...competitors.map(c => c.rating)),
    };
    
    return competitors.map(c => ({
      name: c.name,
      adSpend: (c.adSpend / maxValues.adSpend) * 100,
      marketShare: (c.marketShare / maxValues.marketShare) * 100,
      productCount: (c.productCount / maxValues.productCount) * 100,
      rating: (c.rating / maxValues.rating) * 100,
    }));
  }, [competitors]);

  const handleRefresh = () => {
    setLoading(true);
    setTimeout(() => {
      setLoading(false);
    }, 1000);
  };

  const handleExport = () => {
    const dataStr = JSON.stringify(campaigns, null, 2);
    const blob = new Blob([dataStr], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `campaigns_${moment().format('YYYY-MM-DD')}.json`;
    a.click();
  };

  return (
    <div className="marketing" style={{ padding: 24 }}>
      <Row justify="space-between" align="middle" style={{ marginBottom: 24 }}>
        <Col>
          <Title level={4}>营销管理</Title>
          <Text type="secondary">监控广告投放效果，优化营销策略</Text>
        </Col>
        <Col>
          <Space>
            <RangePicker />
            <Button icon={<ReloadOutlined />} onClick={handleRefresh} loading={loading}>
              刷新
            </Button>
            <Button icon={<ExportOutlined />} onClick={handleExport}>
              导出
            </Button>
          </Space>
        </Col>
      </Row>

      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col xs={12} sm={6}>
          <Card>
            <Statistic
              title="总广告支出"
              value={stats.totalSpend}
              precision={2}
              prefix={<DollarOutlined />}
              valueStyle={{ color: '#cf1322' }}
              suffix="USD"
            />
          </Card>
        </Col>
        <Col xs={12} sm={6}>
          <Card>
            <Statistic
              title="总收入"
              value={stats.totalRevenue}
              precision={2}
              prefix={<RiseOutlined />}
              valueStyle={{ color: '#3f8600' }}
              suffix="USD"
            />
          </Card>
        </Col>
        <Col xs={12} sm={6}>
          <Card>
            <Statistic
              title="总点击量"
              value={stats.totalClicks}
              prefix={<EyeOutlined />}
            />
          </Card>
        </Col>
        <Col xs={12} sm={6}>
          <Card>
            <Statistic
              title="转化数"
              value={stats.totalConversions}
              prefix={<ShoppingCartOutlined />}
            />
          </Card>
        </Col>
      </Row>

      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col xs={8}>
          <Card size="small">
            <Statistic
              title="展示量"
              value={stats.totalImpressions}
              prefix={<EyeOutlined />}
              valueStyle={{ fontSize: 16 }}
            />
          </Card>
        </Col>
        <Col xs={8}>
          <Card size="small">
            <Statistic
              title="平均CTR"
              value={stats.avgCTR}
              precision={2}
              suffix="%"
              valueStyle={{ fontSize: 16 }}
            />
          </Card>
        </Col>
        <Col xs={8}>
          <Card size="small">
            <Statistic
              title="平均ROAS"
              value={stats.avgROAS}
              precision={2}
              suffix="x"
              valueStyle={{ fontSize: 16, color: stats.avgROAS >= 3 ? '#3f8600' : '#faad14' }}
            />
          </Card>
        </Col>
      </Row>

      <Tabs 
        activeKey={activeTab} 
        onChange={setActiveTab}
        items={[
          {
            key: 'overview',
            label: (
              <span>
                <LineChartOutlined />
                营销概览
              </span>
            ),
            children: (
              <Row gutter={16}>
                <Col xs={24} lg={16}>
                  <Card title="广告收支趋势" size="small">
                    <ResponsiveContainer width="100%" height={280}>
                      <LineChart
                        data={trendData}
                        margin={{ top: 5, right: 30, left: 20, bottom: 5 }}
                      >
                        <CartesianGrid strokeDasharray="3 3" />
                        <XAxis dataKey="date" />
                        <YAxis yAxisId="left" />
                        <YAxis yAxisId="right" orientation="right" />
                        <Tooltip />
                        <Legend />
                        <Line yAxisId="left" type="monotone" dataKey="spend" name="支出" stroke="#ff4d4f" activeDot={{ r: 8 }} />
                        <Line yAxisId="right" type="monotone" dataKey="revenue" name="收入" stroke="#52c41a" activeDot={{ r: 8 }} />
                      </LineChart>
                    </ResponsiveContainer>
                  </Card>
                </Col>
                <Col xs={24} lg={8}>
                  <Card title="渠道效果对比" size="small">
                    <ResponsiveContainer width="100%" height={280}>
                      <BarChart
                        data={platformData}
                        margin={{ top: 5, right: 30, left: 20, bottom: 5 }}
                      >
                        <CartesianGrid strokeDasharray="3 3" />
                        <XAxis dataKey="platform" />
                        <YAxis />
                        <Tooltip />
                        <Legend />
                        <Bar dataKey="spend" name="支出" fill="#ff4d4f" />
                        <Bar dataKey="revenue" name="收入" fill="#52c41a" />
                      </BarChart>
                    </ResponsiveContainer>
                  </Card>
                </Col>
                <Col span={24} style={{ marginTop: 16 }}>
                  <Card title="转化趋势" size="small">
                    <ResponsiveContainer width="100%" height={250}>
                      <LineChart
                        data={trendData}
                        margin={{ top: 5, right: 30, left: 20, bottom: 5 }}
                      >
                        <CartesianGrid strokeDasharray="3 3" />
                        <XAxis dataKey="date" />
                        <YAxis />
                        <Tooltip />
                        <Legend />
                        <Line type="monotone" dataKey="conversions" name="转化数" stroke="#1890ff" activeDot={{ r: 8 }} />
                      </LineChart>
                    </ResponsiveContainer>
                  </Card>
                </Col>
              </Row>
            ),
          },
          {
            key: 'channels',
            label: (
              <span>
                <BarChartOutlined />
                渠道分析
              </span>
            ),
            children: (
              <Row gutter={16}>
                <Col xs={24} lg={12}>
                  <Card title="各平台广告效果" size="small">
                    <Table
                      columns={[
                        { title: '平台', dataIndex: 'platform', key: 'platform' },
                        { title: '支出', dataIndex: 'spend', key: 'spend', render: (v) => `$${v.toLocaleString()}` },
                        { title: '收入', dataIndex: 'revenue', key: 'revenue', render: (v) => `$${v.toLocaleString()}` },
                        { title: 'ROAS', dataIndex: 'roas', key: 'roas', render: (v) => <Text style={{ color: v >= 3 ? '#52c41a' : '#faad14' }}>{v.toFixed(2)}x</Text> },
                        { title: '转化', dataIndex: 'conversions', key: 'conversions', render: (v) => v.toLocaleString() },
                      ]}
                      dataSource={platformData}
                      rowKey="platform"
                      pagination={false}
                      size="small"
                    />
                  </Card>
                </Col>
                <Col xs={24} lg={12}>
                  <Card title="渠道占比" size="small">
                    <ResponsiveContainer width="100%" height={300}>
                      <Pie
                        data={platformData.map(d => ({ name: d.platform, value: d.spend }))}
                        cx="50%"
                        cy="50%"
                        labelLine={false}
                        outerRadius={100}
                        fill="#8884d8"
                        dataKey="value"
                        label={({ name, percent }) => `${name}: ${((percent || 0) * 100).toFixed(0)}%`}
                      >
                        {platformData.map((entry, index) => (
                          <Cell key={`cell-${index}`} fill={['#1890ff', '#52c41a', '#faad14', '#ff4d4f', '#722ed1', '#eb2f96'][index % 6]} />
                        ))}
                      </Pie>
                    </ResponsiveContainer>
                  </Card>
                </Col>
                <Col span={24} style={{ marginTop: 16 }}>
                  <Card title="渠道洞察" size="small">
                    <Alert
                      message="渠道分析洞察"
                      description={
                        <ul style={{ margin: 0, paddingLeft: 20 }}>
                          <li>Amazon 渠道表现最佳，ROAS 达到 4.2x，建议继续加大投入</li>
                          <li>Shopee 渠道 ROAS 最高（5.1x），但转化数较少，可优化关键词</li>
                          <li>Shopify 渠道 ROAS 较低（2.9x），建议调整广告策略或暂停</li>
                          <li>Google 渠道已结束，建议重新评估投放策略</li>
                        </ul>
                      }
                      type="info"
                      showIcon
                    />
                  </Card>
                </Col>
              </Row>
            ),
          },
          {
            key: 'competitors',
            label: (
              <span>
                <TrophyOutlined />
                竞争对手分析
              </span>
            ),
            children: (
              <Row gutter={16}>
                <Col xs={24} lg={12}>
                  <Card title="竞争对手综合对比" size="small">
                    <ResponsiveContainer width="100%" height={350}>
                      <RadarChart
                        data={competitorRadarData}
                        margin={{ top: 20, right: 20, bottom: 20, left: 20 }}
                      >
                        <PolarGrid />
                        <PolarAngleAxis dataKey="name" />
                        <PolarRadiusAxis angle={90} domain={[0, 100]} />
                        <Radar
                          name="广告支出"
                          dataKey="adSpend"
                          stroke="#1890ff"
                          fill="#1890ff"
                          fillOpacity={0.3}
                        />
                        <Radar
                          name="市场份额"
                          dataKey="marketShare"
                          stroke="#52c41a"
                          fill="#52c41a"
                          fillOpacity={0.3}
                        />
                        <Radar
                          name="商品数量"
                          dataKey="productCount"
                          stroke="#faad14"
                          fill="#faad14"
                          fillOpacity={0.3}
                        />
                        <Radar
                          name="评分"
                          dataKey="rating"
                          stroke="#ff4d4f"
                          fill="#ff4d4f"
                          fillOpacity={0.3}
                        />
                        <Legend />
                      </RadarChart>
                    </ResponsiveContainer>
                  </Card>
                </Col>
                <Col xs={24} lg={12}>
                  <Card title="竞争对手排名" size="small">
                    <Table
                      columns={competitorColumns}
                      dataSource={competitors}
                      rowKey="id"
                      pagination={false}
                      size="small"
                    />
                  </Card>
                </Col>
                <Col span={24} style={{ marginTop: 16 }}>
                  <Card title="竞争策略建议" size="small">
                    <Row gutter={16}>
                      <Col span={8}>
                        <div style={{ textAlign: 'center', padding: 16 }}>
                          <WarningOutlined style={{ fontSize: 32, color: '#52c41a' }} />
                          <div style={{ marginTop: 8, fontWeight: 500 }}>价格策略</div>
                          <Text type="secondary" style={{ fontSize: 12 }}>竞争对手平均价格为 $89.99，建议保持价格竞争力</Text>
                        </div>
                      </Col>
                      <Col span={8}>
                        <div style={{ textAlign: 'center', padding: 16 }}>
                          <FireOutlined style={{ fontSize: 32, color: '#ff4d4f' }} />
                          <div style={{ marginTop: 8, fontWeight: 500 }}>广告策略</div>
                          <Text type="secondary" style={{ fontSize: 12 }}>竞争对手广告支出较高，建议增加投放预算</Text>
                        </div>
                      </Col>
                      <Col span={8}>
                        <div style={{ textAlign: 'center', padding: 16 }}>
                          <StarOutlined style={{ fontSize: 32, color: '#faad14' }} />
                          <div style={{ marginTop: 8, fontWeight: 500 }}>产品策略</div>
                          <Text type="secondary" style={{ fontSize: 12 }}>竞争对手平均商品数为 85，建议扩充产品线</Text>
                        </div>
                      </Col>
                    </Row>
                  </Card>
                </Col>
              </Row>
            ),
          },
          {
            key: 'ads',
            label: (
              <span>
                <ThunderboltOutlined />
                广告管理
              </span>
            ),
            children: (
              <Card>
                <Row justify="space-between" align="middle" style={{ marginBottom: 16 }}>
                  <Col>
                    <Space>
                      <Select defaultValue="all" style={{ width: 120 }}>
                        <Option value="all">全部平台</Option>
                        <Option value="amazon">Amazon</Option>
                        <Option value="ebay">eBay</Option>
                        <Option value="shopify">Shopify</Option>
                        <Option value="shopee">Shopee</Option>
                        <Option value="google">Google</Option>
                      </Select>
                      <Select defaultValue="all" style={{ width: 100 }}>
                        <Option value="all">全部状态</Option>
                        <Option value="active">投放中</Option>
                        <Option value="paused">已暂停</Option>
                        <Option value="completed">已结束</Option>
                      </Select>
                    </Space>
                  </Col>
                  <Col>
                    <Space>
                      <Button icon={<ReloadOutlined />} onClick={handleRefresh} loading={loading}>
                        刷新
                      </Button>
                      <Button icon={<ExportOutlined />} onClick={handleExport}>
                        导出
                      </Button>
                    </Space>
                  </Col>
                </Row>
                <Table
                  columns={campaignColumns}
                  dataSource={campaigns}
                  rowKey="id"
                  pagination={{ pageSize: 10 }}
                  loading={loading}
                />
              </Card>
            ),
          },
        ]}
      />

      <Row gutter={16} style={{ marginTop: 24 }}>
        <Col span={8}>
          <Button type="primary" block onClick={() => navigate('/dashboard/marketing/ads')}>
            广告管理
          </Button>
        </Col>
        <Col span={8}>
          <Button type="primary" block onClick={() => navigate('/dashboard/marketing/competitors')}>
            竞争对手分析
          </Button>
        </Col>
        <Col span={8}>
          <Button type="primary" block onClick={() => navigate('/dashboard/reports/performance')}>
            营销绩效报表
          </Button>
        </Col>
      </Row>

      <Drawer
        title="广告详情"
        placement="right"
        onClose={() => setDetailDrawerVisible(false)}
        open={detailDrawerVisible}
        width={600}
      >
        {selectedCampaign && (
          <Descriptions column={1} bordered>
            <Descriptions.Item label="广告系列">{selectedCampaign.name}</Descriptions.Item>
            <Descriptions.Item label="平台">{selectedCampaign.platform}</Descriptions.Item>
            <Descriptions.Item label="状态">
              <Tag color={statusColors[selectedCampaign.status]}>{statusTexts[selectedCampaign.status]}</Tag>
            </Descriptions.Item>
            <Descriptions.Item label="预算">${selectedCampaign.budget.toLocaleString()}</Descriptions.Item>
            <Descriptions.Item label="已花费">${selectedCampaign.spent.toLocaleString()}</Descriptions.Item>
            <Descriptions.Item label="预算使用率">
              <Progress percent={Math.round((selectedCampaign.spent / selectedCampaign.budget) * 100)} />
            </Descriptions.Item>
            <Descriptions.Item label="展示量">{selectedCampaign.impressions.toLocaleString()}</Descriptions.Item>
            <Descriptions.Item label="点击量">{selectedCampaign.clicks.toLocaleString()}</Descriptions.Item>
            <Descriptions.Item label="CTR">{selectedCampaign.ctr}%</Descriptions.Item>
            <Descriptions.Item label="转化数">{selectedCampaign.conversions.toLocaleString()}</Descriptions.Item>
            <Descriptions.Item label="ROAS">
              <Text style={{ color: selectedCampaign.roas >= 3 ? '#52c41a' : selectedCampaign.roas >= 2 ? '#faad14' : '#ff4d4f' }}>
                {selectedCampaign.roas}x
              </Text>
            </Descriptions.Item>
            <Descriptions.Item label="开始时间">{moment(selectedCampaign.startDate).format('YYYY-MM-DD')}</Descriptions.Item>
            {selectedCampaign.endDate && (
              <Descriptions.Item label="结束时间">{moment(selectedCampaign.endDate).format('YYYY-MM-DD')}</Descriptions.Item>
            )}
          </Descriptions>
        )}
      </Drawer>
    </div>
  );
};

export default Marketing;