import React, { useState } from 'react';
import { Card, Typography, Row, Col, Form, Input, Select, Button, Table, Statistic, Spin, message, Alert } from 'antd';
import { LineChart, Line, BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer, PieChart, Pie, Cell } from 'recharts';
import { RocketOutlined, SaveOutlined, BarChartOutlined, TargetOutlined, ReloadOutlined } from '@ant-design/icons';
import { Link } from 'umi';
import { adOptimizationDataSource, OptimizationSuggestion, AdPerformance } from '@/services/adOptimizationDataSource';

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

const AIOptimization: React.FC = () => {
  const [loading, setLoading] = useState<boolean>(false);
  const [optimizationSuggestions, setOptimizationSuggestions] = useState<OptimizationSuggestion[]>([]);
  const [adPerformance, setAdPerformance] = useState<AdPerformance[]>([]);
  const [form] = Form.useForm();

  const handleOptimizeAds = async () => {
    setLoading(true);
    try {
      const data = await adOptimizationDataSource.optimize();
      setOptimizationSuggestions(data.suggestions);
      setAdPerformance(data.performance);
      message.success('广告优化分析完成');
    } catch (error) {
      message.error('广告优化分析失败');
    } finally {
      setLoading(false);
    }
  };

  const handleApplyOptimization = async (id: string) => {
    try {
      await adOptimizationDataSource.applySuggestion(id);
      const updatedSuggestions = optimizationSuggestions.map(item => 
        item.id === id ? { ...item, status: 'applied' as const } : item
      );
      setOptimizationSuggestions(updatedSuggestions);
      message.success('优化建议已应用');
    } catch (error) {
      message.error('应用优化建议失败');
    }
  };

  const handleRejectOptimization = async (id: string) => {
    try {
      await adOptimizationDataSource.rejectSuggestion(id);
      const updatedSuggestions = optimizationSuggestions.map(item => 
        item.id === id ? { ...item, status: 'rejected' as const } : item
      );
      setOptimizationSuggestions(updatedSuggestions);
      message.info('优化建议已拒绝');
    } catch (error) {
      message.error('拒绝优化建议失败');
    }
  };

  const columns = [
    {
      title: '广告ID',
      dataIndex: 'adId',
      key: 'adId',
    },
    {
      title: '广告名称',
      dataIndex: 'adName',
      key: 'adName',
    },
    {
      title: '当前CPC',
      dataIndex: 'currentCPC',
      key: 'currentCPC',
      render: (text: number) => `¥${text}`,
    },
    {
      title: '建议CPC',
      dataIndex: 'suggestedCPC',
      key: 'suggestedCPC',
      render: (text: number, record: OptimizationSuggestion) => (
        <span style={{ color: text < record.currentCPC ? '#52c41a' : '#ff4d4f' }}>
          ¥{text}
        </span>
      ),
    },
    {
      title: '当前ROI',
      dataIndex: 'currentROI',
      key: 'currentROI',
    },
    {
      title: '预期ROI',
      dataIndex: 'expectedROI',
      key: 'expectedROI',
      render: (text: number, record: OptimizationSuggestion) => (
        <span style={{ color: text > record.currentROI ? '#52c41a' : '#ff4d4f' }}>
          {text}
        </span>
      ),
    },
    {
      title: '当前预算',
      dataIndex: 'currentSpend',
      key: 'currentSpend',
      render: (text: number) => `¥${text}`,
    },
    {
      title: '建议预算',
      dataIndex: 'suggestedSpend',
      key: 'suggestedSpend',
      render: (text: number) => `¥${text}`,
    },
    {
      title: '置信度',
      dataIndex: 'confidence',
      key: 'confidence',
      render: (text: number) => `${(text * 100).toFixed(0)}%`,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => (
        <span style={{ 
          color: status === 'pending' ? '#faad14' : 
                 status === 'applied' ? '#52c41a' : '#ff4d4f'
        }}>
          {status === 'pending' ? '待处理' : 
           status === 'applied' ? '已应用' : '已拒绝'}
        </span>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: OptimizationSuggestion) => (
        <div>
          {record.status === 'pending' && (
            <>
              <Button 
                type="primary" 
                size="small"
                onClick={() => handleApplyOptimization(record.id)}
                style={{ marginRight: 8 }}
              >
                应用
              </Button>
              <Button 
                size="small"
                onClick={() => handleRejectOptimization(record.id)}
              >
                拒绝
              </Button>
            </>
          )}
        </div>
      ),
    },
  ];

  // 准备图表数据
  const chartData = mockAdPerformance.map(item => ({
    date: item.date,
    点击量: item.clicks,
    转化量: item.conversions,
  }));

  const roiData = mockAdPerformance.map(item => ({
    date: item.date,
    ROI: item.roi,
  }));

  const spendData = mockAdPerformance.map(item => ({
    date: item.date,
    花费: item.spend,
  }));

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
        <Title level={4}>AI广告优化</Title>
        <Button type="primary" icon={<BarChartOutlined />}>
          <Link to="/Ad/Performance">广告效果</Link>
        </Button>
      </div>

      {/* 优化参数表单 */}
      <Card title="优化参数" style={{ marginBottom: 24 }}>
        <Form
          form={form}
          layout="horizontal"
          initialValues={{
            adCampaign: '所有广告',
            optimizationGoal: 'roi',
            budgetLimit: 5000,
            timeRange: '7d',
          }}
        >
          <Row gutter={[16, 16]}>
            <Col span={6}>
              <Item label="广告活动" name="adCampaign">
                <Select>
                  <Option value="所有广告">所有广告</Option>
                  <Option value="智能手表推广">智能手表推广</Option>
                  <Option value="无线耳机促销">无线耳机促销</Option>
                  <Option value="智能音箱新品">智能音箱新品</Option>
                </Select>
              </Item>
            </Col>
            <Col span={6}>
              <Item label="优化目标" name="optimizationGoal">
                <Select>
                  <Option value="roi">ROI最大化</Option>
                  <Option value="conversion">转化量最大化</Option>
                  <Option value="clicks">点击量最大化</Option>
                  <Option value="spend">预算控制</Option>
                </Select>
              </Item>
            </Col>
            <Col span={6}>
              <Item label="预算限制" name="budgetLimit">
                <Input type="number" prefix="¥" placeholder="输入预算限制" />
              </Item>
            </Col>
            <Col span={6}>
              <Item label="时间范围" name="timeRange">
                <Select>
                  <Option value="7d">近7天</Option>
                  <Option value="30d">近30天</Option>
                  <Option value="90d">近90天</Option>
                </Select>
              </Item>
            </Col>
            <Col span={24} style={{ display: 'flex', justifyContent: 'flex-end' }}>
              <Button 
                type="primary" 
                icon={<RocketOutlined />} 
                onClick={handleOptimizeAds}
                loading={loading}
                size="large"
              >
                开始AI优化
              </Button>
            </Col>
          </Row>
        </Form>
      </Card>

      {/* 广告性能概览 */}
      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        <Col span={6}>
          <Card>
            <Statistic
              title="平均ROI"
              value={mockAdPerformance.reduce((sum, item) => sum + item.roi, 0) / mockAdPerformance.length}
              valueStyle={{ color: '#3f8600' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="总点击量"
              value={mockAdPerformance.reduce((sum, item) => sum + item.clicks, 0)}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="总转化量"
              value={mockAdPerformance.reduce((sum, item) => sum + item.conversions, 0)}
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="总花费"
              value={mockAdPerformance.reduce((sum, item) => sum + item.spend, 0)}
              prefix="¥"
              valueStyle={{ color: '#faad14' }}
            />
          </Card>
        </Col>
      </Row>

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

      {/* 优化建议 */}
      <Card title="AI优化建议">
        {loading ? (
          <div style={{ display: 'flex', justifyContent: 'center', padding: '40px 0' }}>
            <Spin size="large" />
          </div>
        ) : optimizationSuggestions.length > 0 ? (
          <Table 
            columns={columns} 
            dataSource={optimizationSuggestions} 
            rowKey="id"
            pagination={{ pageSize: 10 }}
          />
        ) : (
          <Alert 
            message="请设置优化参数并点击开始AI优化" 
            type="info" 
            showIcon 
            style={{ margin: '20px 0' }}
          />
        )}
      </Card>
    </div>
  );
};

export default AIOptimization;