import React, { useState } from 'react';
import { Card, Typography, Row, Col, Form, Input, Select, Button, Table, Statistic, Spin, message, Alert } from 'antd';
import { CalculatorOutlined, SaveOutlined, HistoryOutlined, LineChartOutlined } from '@ant-design/icons';
import { Link } from 'umi';
import { productDataSource, AIPricingSuggestion } from '@/services/productDataSource';

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

interface PricingSuggestion {
  id: string;
  scenario: string;
  suggestedPrice: number;
  expectedProfit: number;
  expectedROI: number;
  expectedSales: number;
  confidence: number;
}

interface PriceHistory {
  id: string;
  date: string;
  oldPrice: number;
  newPrice: number;
  reason: string;
  operator: string;
}

const AIPricing: React.FC = () => {
  const [loading, setLoading] = useState<boolean>(false);
  const [pricingSuggestions, setPricingSuggestions] = useState<PricingSuggestion[]>([]);
  const [priceHistory, setPriceHistory] = useState<PriceHistory[]>([]);
  const [form] = Form.useForm();

  const mockPricingSuggestions: PricingSuggestion[] = [
    {
      id: '1',
      scenario: '激进定价',
      suggestedPrice: 349,
      expectedProfit: 199,
      expectedROI: 132.67,
      expectedSales: 80,
      confidence: 0.85,
    },
    {
      id: '2',
      scenario: '均衡定价',
      suggestedPrice: 299,
      expectedProfit: 149,
      expectedROI: 99.33,
      expectedSales: 120,
      confidence: 0.95,
    },
    {
      id: '3',
      scenario: '保守定价',
      suggestedPrice: 279,
      expectedProfit: 129,
      expectedROI: 86.00,
      expectedSales: 150,
      confidence: 0.90,
    },
  ];

  const mockPriceHistory: PriceHistory[] = [
    {
      id: '1',
      date: '2026-03-15',
      oldPrice: 279,
      newPrice: 299,
      reason: '基于市场竞争分析',
      operator: 'AI系统',
    },
    {
      id: '2',
      date: '2026-03-10',
      oldPrice: 259,
      newPrice: 279,
      reason: '成本上升',
      operator: '运营专员',
    },
    {
      id: '3',
      date: '2026-03-01',
      oldPrice: 239,
      newPrice: 259,
      reason: '新品上市',
      operator: '运营专员',
    },
  ];

  const handleCalculatePrice = () => {
    setLoading(true);
    // 模拟API请求
    setTimeout(() => {
      setPricingSuggestions(mockPricingSuggestions);
      setPriceHistory(mockPriceHistory);
      setLoading(false);
      message.success('智能定价计算完成');
    }, 1500);
  };

  const handleApplyPrice = (scenario: string, price: number) => {
    message.success(`已应用${scenario}定价策略，新价格：¥${price}`);
  };

  const columns = [
    {
      title: '场景',
      dataIndex: 'scenario',
      key: 'scenario',
    },
    {
      title: '建议售价',
      dataIndex: 'suggestedPrice',
      key: 'suggestedPrice',
      render: (text: number) => `¥${text}`,
    },
    {
      title: '预期利润',
      dataIndex: 'expectedProfit',
      key: 'expectedProfit',
      render: (text: number) => `¥${text}`,
    },
    {
      title: '预期ROI',
      dataIndex: 'expectedROI',
      key: 'expectedROI',
      render: (text: number) => `${text}%`,
    },
    {
      title: '预期销量',
      dataIndex: 'expectedSales',
      key: 'expectedSales',
    },
    {
      title: '置信度',
      dataIndex: 'confidence',
      key: 'confidence',
      render: (text: number) => `${(text * 100).toFixed(0)}%`,
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: PricingSuggestion) => (
        <Button 
          type="primary" 
          size="small"
          onClick={() => handleApplyPrice(record.scenario, record.suggestedPrice)}
        >
          应用
        </Button>
      ),
    },
  ];

  const historyColumns = [
    {
      title: '日期',
      dataIndex: 'date',
      key: 'date',
    },
    {
      title: '旧价格',
      dataIndex: 'oldPrice',
      key: 'oldPrice',
      render: (text: number) => `¥${text}`,
    },
    {
      title: '新价格',
      dataIndex: 'newPrice',
      key: 'newPrice',
      render: (text: number) => `¥${text}`,
    },
    {
      title: '调整原因',
      dataIndex: 'reason',
      key: 'reason',
    },
    {
      title: '操作人',
      dataIndex: 'operator',
      key: 'operator',
    },
  ];

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
        <Title level={4}>AI智能定价</Title>
        <Button type="primary" icon={<HistoryOutlined />}>
          <Link to="/Product/PriceHistory">价格历史</Link>
        </Button>
      </div>

      {/* 定价参数表单 */}
      <Card title="定价参数" style={{ marginBottom: 24 }}>
        <Form
          form={form}
          layout="horizontal"
          initialValues={{
            productId: 'P001',
            cost: 150,
            currentPrice: 299,
            competitorPrice: 329,
            salesVolume: 120,
            pricingStrategy: 'balanced',
          }}
        >
          <Row gutter={[16, 16]}>
            <Col span={6}>
              <Item label="商品ID" name="productId">
                <Input placeholder="输入商品ID" />
              </Item>
            </Col>
            <Col span={6}>
              <Item label="成本" name="cost" rules={[{ required: true, message: '请输入成本' }]}>
                <Input type="number" prefix="¥" placeholder="输入成本" />
              </Item>
            </Col>
            <Col span={6}>
              <Item label="当前售价" name="currentPrice" rules={[{ required: true, message: '请输入当前售价' }]}>
                <Input type="number" prefix="¥" placeholder="输入当前售价" />
              </Item>
            </Col>
            <Col span={6}>
              <Item label="竞品价格" name="competitorPrice">
                <Input type="number" prefix="¥" placeholder="输入竞品价格" />
              </Item>
            </Col>
            <Col span={6}>
              <Item label="月销量" name="salesVolume">
                <Input type="number" placeholder="输入月销量" />
              </Item>
            </Col>
            <Col span={6}>
              <Item label="定价策略" name="pricingStrategy">
                <Select>
                  <Option value="aggressive">激进定价</Option>
                  <Option value="balanced">均衡定价</Option>
                  <Option value="conservative">保守定价</Option>
                </Select>
              </Item>
            </Col>
            <Col span={12} style={{ display: 'flex', alignItems: 'flex-end' }}>
              <Button 
                type="primary" 
                icon={<CalculatorOutlined />} 
                onClick={handleCalculatePrice}
                loading={loading}
                style={{ width: '100%' }}
              >
                计算智能定价
              </Button>
            </Col>
          </Row>
        </Form>
      </Card>

      {/* 定价建议 */}
      <Card title="智能定价建议" style={{ marginBottom: 24 }}>
        {loading ? (
          <div style={{ display: 'flex', justifyContent: 'center', padding: '40px 0' }}>
            <Spin size="large" />
          </div>
        ) : pricingSuggestions.length > 0 ? (
          <Table 
            columns={columns} 
            dataSource={pricingSuggestions} 
            rowKey="id"
            pagination={false}
          />
        ) : (
          <Alert 
            message="请输入定价参数并点击计算按钮" 
            type="info" 
            showIcon 
            style={{ margin: '20px 0' }}
          />
        )}
      </Card>

      {/* 价格历史 */}
      <Card title="价格调整历史">
        <Table 
          columns={historyColumns} 
          dataSource={priceHistory} 
          rowKey="id"
          pagination={{ pageSize: 5 }}
        />
      </Card>
    </div>
  );
};

export default AIPricing;