import React, { useState, useEffect } from 'react';
import { Card, Typography, Row, Col, Select, Button, Table, Statistic, Spin, message, Alert, Badge, Dropdown, Menu } from 'antd';
import { LineChart, Line, BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer, PieChart, Pie, Cell } from 'recharts';
import { ReloadOutlined, ExportOutlined, FilterOutlined, BellOutlined, EyeOutlined } from '@ant-design/icons';
import { Link } from 'umi';
import { marketingDataSource, Ad } from '@/services/marketingDataSource';

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

interface AdPerformance {
  id: string;
  adId: string;
  adName: string;
  clicks: number;
  impressions: number;
  conversions: number;
  spend: number;
  roi: number;
  ctr: number;
  cvr: number;
  cpc: number;
  status: 'normal' | 'warning' | 'error';
}

interface TrendData {
  date: string;
  clicks: number;
  conversions: number;
  spend: number;
  roi: number;
}

interface Anomaly {
  id: string;
  adId: string;
  adName: string;
  type: string;
  message: string;
  severity: 'info' | 'warning' | 'error';
  date: string;
}

const Performance: React.FC = () => {
  const [loading, setLoading] = useState<boolean>(false);
  const [adPerformance, setAdPerformance] = useState<AdPerformance[]>([]);
  const [trendData, setTrendData] = useState<TrendData[]>([]);
  const [anomalies, setAnomalies] = useState<Anomaly[]>([]);
  const [selectedAd, setSelectedAd] = useState<string>('');
  const [timeRange, setTimeRange] = useState<string>('7d');

  const mockAdPerformance: AdPerformance[] = [
    {
      id: '1',
      adId: 'AD001',
      adName: '智能手表推广',
      clicks: 1200,
      impressions: 15000,
      conversions: 120,
      spend: 1800,
      roi: 3.2,
      ctr: 8.0,
      cvr: 10.0,
      cpc: 1.5,
      status: 'normal',
    },
    {
      id: '2',
      adId: 'AD002',
      adName: '无线耳机促销',
      clicks: 2000,
      impressions: 25000,
      conversions: 200,
      spend: 1600,
      roi: 4.5,
      ctr: 8.0,
      cvr: 10.0,
      cpc: 0.8,
      status: 'normal',
    },
    {
      id: '3',
      adName: '智能音箱新品',
      adId: 'AD003',
      clicks: 800,
      impressions: 12000,
      conversions: 40,
      spend: 1600,
      roi: 1.5,
      ctr: 6.7,
      cvr: 5.0,
      cpc: 2.0,
      status: 'warning',
    },
  ];

  const mockTrendData: TrendData[] = [
    { date: '2026-03-12', clicks: 1200, conversions: 120, spend: 1800, roi: 3.2 },
    { date: '2026-03-13', clicks: 1300, conversions: 135, spend: 1950, roi: 3.4 },
    { date: '2026-03-14', clicks: 1100, conversions: 105, spend: 1650, roi: 3.1 },
    { date: '2026-03-15', clicks: 1400, conversions: 150, spend: 2100, roi: 3.3 },
    { date: '2026-03-16', clicks: 1500, conversions: 165, spend: 2250, roi: 3.5 },
    { date: '2026-03-17', clicks: 1600, conversions: 180, spend: 2400, roi: 3.6 },
    { date: '2026-03-18', clicks: 1700, conversions: 195, spend: 2550, roi: 3.8 },
  ];

  const mockAnomalies: Anomaly[] = [
    {
      id: '1',
      adId: 'AD003',
      adName: '智能音箱新品',
      type: 'ROI异常',
      message: 'ROI低于2.0，建议调整广告策略',
      severity: 'warning',
      date: '2026-03-18 10:30',
    },
    {
      id: '2',
      adId: 'AD001',
      adName: '智能手表推广',
      type: '点击率下降',
      message: 'CTR下降20%，建议优化创意',
      severity: 'info',
      date: '2026-03-18 09:15',
    },
  ];

  const fetchPerformanceData = () => {
    setLoading(true);
    // 模拟API请求
    setTimeout(() => {
      setAdPerformance(mockAdPerformance);
      setTrendData(mockTrendData);
      setAnomalies(mockAnomalies);
      setLoading(false);
    }, 1000);
  };

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

  const handleAdChange = (value: string) => {
    setSelectedAd(value);
  };

  const handleTimeRangeChange = (value: string) => {
    setTimeRange(value);
  };

  const handleRefresh = () => {
    fetchPerformanceData();
  };

  const handleExport = () => {
    message.success('报告已导出');
  };

  const columns = [
    {
      title: '广告ID',
      dataIndex: 'adId',
      key: 'adId',
    },
    {
      title: '广告名称',
      dataIndex: 'adName',
      key: 'adName',
    },
    {
      title: '点击量',
      dataIndex: 'clicks',
      key: 'clicks',
    },
    {
      title: '展示量',
      dataIndex: 'impressions',
      key: 'impressions',
    },
    {
      title: '转化量',
      dataIndex: 'conversions',
      key: 'conversions',
    },
    {
      title: '花费',
      dataIndex: 'spend',
      key: 'spend',
      render: (text: number) => `¥${text}`,
    },
    {
      title: 'ROI',
      dataIndex: 'roi',
      key: 'roi',
      render: (text: number, record: AdPerformance) => (
        <span style={{ 
          color: record.status === 'error' ? '#ff4d4f' : 
                 record.status === 'warning' ? '#faad14' : '#52c41a'
        }}>
          {text}
        </span>
      ),
    },
    {
      title: 'CTR',
      dataIndex: 'ctr',
      key: 'ctr',
      render: (text: number) => `${text}%`,
    },
    {
      title: 'CVR',
      dataIndex: 'cvr',
      key: 'cvr',
      render: (text: number) => `${text}%`,
    },
    {
      title: 'CPC',
      dataIndex: 'cpc',
      key: 'cpc',
      render: (text: number) => `¥${text}`,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => (
        <Badge 
          status={status === 'normal' ? 'success' : status === 'warning' ? 'warning' : 'error'} 
          text={status === 'normal' ? '正常' : status === 'warning' ? '警告' : '异常'}
        />
      ),
    },
  ];

  const anomalyColumns = [
    {
      title: '广告ID',
      dataIndex: 'adId',
      key: 'adId',
    },
    {
      title: '广告名称',
      dataIndex: 'adName',
      key: 'adName',
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
    },
    {
      title: '消息',
      dataIndex: 'message',
      key: 'message',
    },
    {
      title: '严重程度',
      dataIndex: 'severity',
      key: 'severity',
      render: (severity: string) => (
        <Badge 
          status={severity === 'info' ? 'default' : severity === 'warning' ? 'warning' : 'error'} 
          text={severity === 'info' ? '信息' : severity === 'warning' ? '警告' : '错误'}
        />
      ),
    },
    {
      title: '时间',
      dataIndex: 'date',
      key: 'date',
    },
  ];

  // 计算总体指标
  const totalClicks = mockAdPerformance.reduce((sum, item) => sum + item.clicks, 0);
  const totalImpressions = mockAdPerformance.reduce((sum, item) => sum + item.impressions, 0);
  const totalConversions = mockAdPerformance.reduce((sum, item) => sum + item.conversions, 0);
  const totalSpend = mockAdPerformance.reduce((sum, item) => sum + item.spend, 0);
  const avgROI = mockAdPerformance.reduce((sum, item) => sum + item.roi, 0) / mockAdPerformance.length;
  const avgCTR = mockAdPerformance.reduce((sum, item) => sum + item.ctr, 0) / mockAdPerformance.length;
  const avgCVR = mockAdPerformance.reduce((sum, item) => sum + item.cvr, 0) / mockAdPerformance.length;

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
        <Title level={4}>广告效果监控</Title>
        <div style={{ display: 'flex', gap: 12 }}>
          <Select
            placeholder="选择广告"
            style={{ width: 200 }}
            onChange={handleAdChange}
          >
            <Option value="">全部广告</Option>
            <Option value="AD001">智能手表推广</Option>
            <Option value="AD002">无线耳机促销</Option>
            <Option value="AD003">智能音箱新品</Option>
          </Select>
          <Select
            defaultValue="7d"
            style={{ width: 120 }}
            onChange={handleTimeRangeChange}
          >
            <Option value="7d">近7天</Option>
            <Option value="30d">近30天</Option>
            <Option value="90d">近90天</Option>
          </Select>
          <Button 
            type="primary" 
            icon={<ReloadOutlined />} 
            onClick={handleRefresh}
            loading={loading}
          >
            刷新
          </Button>
          <Button icon={<ExportOutlined />} onClick={handleExport}>
            导出报告
          </Button>
        </div>
      </div>

      {/* 总体指标 */}
      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        <Col span={6}>
          <Card>
            <Statistic
              title="总点击量"
              value={totalClicks}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="总转化量"
              value={totalConversions}
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="总花费"
              value={totalSpend}
              prefix="¥"
              valueStyle={{ color: '#faad14' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="平均ROI"
              value={avgROI}
              valueStyle={{ color: '#3f8600' }}
            />
          </Card>
        </Col>
      </Row>

      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        <Col span={6}>
          <Card>
            <Statistic
              title="平均CTR"
              value={avgCTR}
              suffix="%"
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="平均CVR"
              value={avgCVR}
              suffix="%"
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="总展示量"
              value={totalImpressions}
              valueStyle={{ color: '#faad14' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="异常预警"
              value={mockAnomalies.length}
              prefix={<BellOutlined />}
              valueStyle={{ color: '#ff4d4f' }}
            />
          </Card>
        </Col>
      </Row>

      {/* 趋势图表 */}
      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        <Col span={12}>
          <Card title="点击量与转化量趋势">
            <ResponsiveContainer width="100%" height={300}>
              <BarChart data={mockTrendData}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="date" />
                <YAxis />
                <Tooltip />
                <Legend />
                <Bar dataKey="clicks" name="点击量" fill="#1890ff" />
                <Bar dataKey="conversions" name="转化量" fill="#52c41a" />
              </BarChart>
            </ResponsiveContainer>
          </Card>
        </Col>
        <Col span={12}>
          <Card title="ROI趋势">
            <ResponsiveContainer width="100%" height={300}>
              <LineChart data={mockTrendData}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="date" />
                <YAxis />
                <Tooltip />
                <Legend />
                <Line type="monotone" dataKey="roi" name="ROI" stroke="#ff4d4f" strokeWidth={2} />
              </LineChart>
            </ResponsiveContainer>
          </Card>
        </Col>
      </Row>

      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        <Col span={24}>
          <Card title="花费趋势">
            <ResponsiveContainer width="100%" height={300}>
              <LineChart data={mockTrendData}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="date" />
                <YAxis />
                <Tooltip />
                <Legend />
                <Line type="monotone" dataKey="spend" name="花费" stroke="#faad14" strokeWidth={2} />
              </LineChart>
            </ResponsiveContainer>
          </Card>
        </Col>
      </Row>

      <Row gutter={[16, 16]}>
        {/* 广告性能详情 */}
        <Col span={16}>
          <Card title="广告性能详情">
            <Table 
              columns={columns} 
              dataSource={mockAdPerformance} 
              rowKey="id" 
              loading={loading}
              pagination={{ pageSize: 10 }}
            />
          </Card>
        </Col>

        {/* 异常预警 */}
        <Col span={8}>
          <Card title="异常预警">
            <Table 
              columns={anomalyColumns} 
              dataSource={mockAnomalies} 
              rowKey="id" 
              loading={loading}
              pagination={{ pageSize: 5 }}
            />
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default Performance;