import React, { useState, useEffect } from 'react';
import { Card, Row, Col, Select, DatePicker, Button, Table } from 'antd';
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer, BarChart, Bar } from 'recharts';
import { inventoryDataSource, InventoryForecast as InventoryForecastType } from '@/services/inventoryDataSource';

const { Option } = Select;
const { RangePicker } = DatePicker;

interface ForecastData {
  date: string;
  demand: number;
  supply: number;
  stock: number;
}

interface ProductForecast {
  id: string;
  sku: string;
  name: string;
  currentStock: number;
  forecastedDemand: number;
  recommendedOrder: number;
  leadTime: number;
  riskLevel: 'low' | 'medium' | 'high';
}

const InventoryForecast: React.FC = () => {
  const [forecastData, setForecastData] = useState<ForecastData[]>([]);
  const [productForecasts, setProductForecasts] = useState<ProductForecast[]>([]);
  const [loading, setLoading] = useState(false);
  const [selectedProduct, setSelectedProduct] = useState('all');
  const [dateRange, setDateRange] = useState<any>(null);

  useEffect(() => {
    fetchForecastData();
  }, [selectedProduct, dateRange]);

  const fetchForecastData = async () => {
    setLoading(true);
    // 模拟API调用
    setTimeout(() => {
      // 模拟预测数据
      const mockForecastData: ForecastData[] = Array.from({ length: 30 }, (_, i) => ({
        date: `2026-04-${String(i + 1).padStart(2, '0')}`,
        demand: Math.random() * 50 + 20,
        supply: Math.random() * 30 + 10,
        stock: Math.random() * 100 + 50,
      }));

      // 模拟产品预测数据
      const mockProductForecasts: ProductForecast[] = [
        {
          id: '1',
          sku: 'SKU-001',
          name: 'Product 1',
          currentStock: 100,
          forecastedDemand: 150,
          recommendedOrder: 100,
          leadTime: 7,
          riskLevel: 'low',
        },
        {
          id: '2',
          sku: 'SKU-002',
          name: 'Product 2',
          currentStock: 15,
          forecastedDemand: 50,
          recommendedOrder: 40,
          leadTime: 10,
          riskLevel: 'high',
        },
        {
          id: '3',
          sku: 'SKU-003',
          name: 'Product 3',
          currentStock: 0,
          forecastedDemand: 30,
          recommendedOrder: 30,
          leadTime: 5,
          riskLevel: 'high',
        },
        {
          id: '4',
          sku: 'SKU-004',
          name: 'Product 4',
          currentStock: 50,
          forecastedDemand: 60,
          recommendedOrder: 20,
          leadTime: 3,
          riskLevel: 'medium',
        },
      ];

      setForecastData(mockForecastData);
      setProductForecasts(mockProductForecasts);
      setLoading(false);
    }, 500);
  };

  const columns = [
    {
      title: 'SKU',
      dataIndex: 'sku',
      key: 'sku',
    },
    {
      title: '商品名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '当前库存',
      dataIndex: 'currentStock',
      key: 'currentStock',
    },
    {
      title: '预测需求',
      dataIndex: 'forecastedDemand',
      key: 'forecastedDemand',
    },
    {
      title: '建议订购量',
      dataIndex: 'recommendedOrder',
      key: 'recommendedOrder',
    },
    {
      title: '交货期(天)',
      dataIndex: 'leadTime',
      key: 'leadTime',
    },
    {
      title: '风险等级',
      dataIndex: 'riskLevel',
      key: 'riskLevel',
      render: (riskLevel: string) => {
        const riskMap = {
          low: { text: '低', color: '#3f8600' },
          medium: { text: '中', color: '#fa8c16' },
          high: { text: '高', color: '#cf1322' },
        };
        const riskInfo = riskMap[riskLevel as keyof typeof riskMap] || { text: riskLevel, color: '#000' };
        return <span style={{ color: riskInfo.color, fontWeight: 'bold' }}>{riskInfo.text}</span>;
      },
    },
  ];

  return (
    <div className="inventory-forecast">
      <div className="page-header">
        <h1>库存预测</h1>
      </div>

      <div className="filter-section" style={{ marginBottom: 24, display: 'flex', gap: 16, flexWrap: 'wrap' }}>
        <Select
          placeholder="选择商品"
          style={{ width: 200 }}
          onChange={setSelectedProduct}
        >
          <Option value="all">全部商品</Option>
          <Option value="SKU-001">SKU-001</Option>
          <Option value="SKU-002">SKU-002</Option>
          <Option value="SKU-003">SKU-003</Option>
        </Select>
        <RangePicker
          style={{ width: 300 }}
          onChange={setDateRange}
        />
        <Button onClick={fetchForecastData}>
          刷新数据
        </Button>
      </div>

      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={24}>
          <Card title="库存趋势预测">
            <ResponsiveContainer width="100%" height={400}>
              <LineChart data={forecastData}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="date" />
                <YAxis />
                <Tooltip />
                <Legend />
                <Line type="monotone" dataKey="demand" stroke="#8884d8" name="需求" />
                <Line type="monotone" dataKey="supply" stroke="#82ca9d" name="供应" />
                <Line type="monotone" dataKey="stock" stroke="#ff7300" name="库存" />
              </LineChart>
            </ResponsiveContainer>
          </Card>
        </Col>
      </Row>

      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={12}>
          <Card title="商品库存预测">
            <ResponsiveContainer width="100%" height={400}>
              <BarChart data={productForecasts}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="name" />
                <YAxis />
                <Tooltip />
                <Legend />
                <Bar dataKey="currentStock" fill="#8884d8" name="当前库存" />
                <Bar dataKey="forecastedDemand" fill="#82ca9d" name="预测需求" />
                <Bar dataKey="recommendedOrder" fill="#ff7300" name="建议订购" />
              </BarChart>
            </ResponsiveContainer>
          </Card>
        </Col>
        <Col span={12}>
          <Card title="商品库存风险">
            <Table
              columns={columns}
              dataSource={productForecasts}
              loading={loading}
              rowKey="id"
              pagination={false}
            />
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default InventoryForecast;