import React, { useState, useEffect } from 'react';
import {
  Card,
  Form,
  Input,
  Select,
  Button,
  Table,
  Modal,
  message,
  Spin,
  Row,
  Col,
  Typography,
  Divider,
  Space,
  Tag,
  Descriptions,
  Statistic,
} from 'antd';
import {
  CalculatorOutlined,
  TruckOutlined,
  PlaneOutlined,
  ShipOutlined,
  DollarOutlined,
  ArrowRightOutlined,
} from '@ant-design/icons';

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

// 模拟物流商数据
const logisticsProviders = [
  {
    id: 'SF',
    name: '顺丰速运',
    icon: <TruckOutlined />,
    basePrice: 12.00,
    pricePerKg: 2.00,
    minDays: 1,
    maxDays: 2,
  },
  {
    id: 'ZTO',
    name: '中通快递',
    icon: <TruckOutlined />,
    basePrice: 8.00,
    pricePerKg: 1.50,
    minDays: 2,
    maxDays: 3,
  },
  {
    id: 'EMS',
    name: 'EMS',
    icon: <PlaneOutlined />,
    basePrice: 15.00,
    pricePerKg: 3.00,
    minDays: 1,
    maxDays: 2,
  },
  {
    id: 'YUNDA',
    name: '韵达快递',
    icon: <TruckOutlined />,
    basePrice: 7.00,
    pricePerKg: 1.20,
    minDays: 3,
    maxDays: 4,
  },
  {
    id: 'DEPPON',
    name: '德邦物流',
    icon: <TruckOutlined />,
    basePrice: 10.00,
    pricePerKg: 1.80,
    minDays: 2,
    maxDays: 3,
  },
];

// 国家/地区选项
const countries = [
  { value: 'CN', label: '中国', rate: 1.00 },
  { value: 'US', label: '美国', rate: 7.00 },
  { value: 'JP', label: '日本', rate: 0.05 },
  { value: 'GB', label: '英国', rate: 8.50 },
  { value: 'DE', label: '德国', rate: 7.50 },
  { value: 'FR', label: '法国', rate: 7.20 },
];

// 模拟历史计算记录
const mockCalculationHistory = [
  {
    id: 'CALC-20260318-001',
    orderId: 'ORD-20260318-001',
    productName: 'Apple iPhone 15 Pro',
    weight: 0.5,
    destination: '北京市朝阳区',
    provider: '顺丰速运',
    cost: 13.00,
    createdAt: '2026-03-18T10:00:00Z',
  },
  {
    id: 'CALC-20260318-002',
    orderId: 'ORD-20260318-002',
    productName: 'MacBook Pro 14',
    weight: 2.0,
    destination: '上海市浦东新区',
    provider: '中通快递',
    cost: 11.00,
    createdAt: '2026-03-18T09:30:00Z',
  },
];

const ShippingCostCalculator: React.FC = () => {
  const [form] = Form.useForm();
  const [isLoading, setIsLoading] = useState(false);
  const [calculationResults, setCalculationResults] = useState<any[]>([]);
  const [showResults, setShowResults] = useState(false);
  const [calculationHistory, setCalculationHistory] = useState(mockCalculationHistory);
  const [selectedCountry, setSelectedCountry] = useState('CN');
  const [exchangeRate, setExchangeRate] = useState(1.00);

  // 处理国家选择
  const handleCountryChange = (value: string) => {
    const country = countries.find(c => c.value === value);
    if (country) {
      setSelectedCountry(value);
      setExchangeRate(country.rate);
    }
  };

  // 处理运费计算
  const handleCalculate = async (values: any) => {
    setIsLoading(true);
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      // 计算各物流商的运费
      const results = logisticsProviders.map(provider => {
        // 基础运费 + 重量 * 每公斤价格
        const baseCost = provider.basePrice + (values.weight * provider.pricePerKg);
        // 转换为目标国家货币
        const convertedCost = baseCost * exchangeRate;
        
        return {
          ...provider,
          cost: convertedCost,
          convertedCost: convertedCost,
        };
      });
      
      // 按价格排序
      results.sort((a, b) => a.cost - b.cost);
      
      setCalculationResults(results);
      setShowResults(true);
      message.success('运费计算成功');
      
      // 添加到历史记录
      const newHistory = {
        id: `CALC-${Date.now()}`,
        orderId: values.orderId || `ORD-${Date.now()}`,
        productName: values.productName,
        weight: values.weight,
        destination: values.destination,
        provider: results[0].name,
        cost: results[0].cost,
        createdAt: new Date().toISOString(),
      };
      
      setCalculationHistory([newHistory, ...calculationHistory]);
    } catch (error) {
      message.error('运费计算失败');
    } finally {
      setIsLoading(false);
    }
  };

  // 计算历史表格列
  const historyColumns = [
    {
      title: '计算ID',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '订单ID',
      dataIndex: 'orderId',
      key: 'orderId',
    },
    {
      title: '商品名称',
      dataIndex: 'productName',
      key: 'productName',
    },
    {
      title: '重量(kg)',
      dataIndex: 'weight',
      key: 'weight',
    },
    {
      title: '目的地',
      dataIndex: 'destination',
      key: 'destination',
    },
    {
      title: '物流商',
      dataIndex: 'provider',
      key: 'provider',
    },
    {
      title: '运费',
      dataIndex: 'cost',
      key: 'cost',
      render: (cost: number) => `¥${cost.toFixed(2)}`,
    },
    {
      title: '计算时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (date: string) => new Date(date).toLocaleString(),
    },
  ];

  return (
    <div style={{ padding: '24px' }}>
      <Card
        title={
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <Title level={4} style={{ margin: 0 }}>运费计算</Title>
            <Text type="secondary">物流策略闭环第二步</Text>
          </div>
        }
        extra={
          <Button type="primary" ghost>
            运费模板管理
          </Button>
        }
      >
        <Divider orientation="left">运费计算</Divider>
        <Form
          form={form}
          layout="vertical"
          onFinish={handleCalculate}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="orderId"
                label="订单ID"
              >
                <Input placeholder="请输入订单ID" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="productName"
                label="商品名称"
                rules={[{ required: true, message: '请输入商品名称' }]}
              >
                <Input placeholder="请输入商品名称" />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={8}>
              <Form.Item
                name="weight"
                label="重量(kg)"
                rules={[{ required: true, message: '请输入重量' }]}
              >
                <Input type="number" step="0.1" placeholder="请输入重量" />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="volume"
                label="体积(m³)"
                rules={[{ required: true, message: '请输入体积' }]}
              >
                <Input type="number" step="0.001" placeholder="请输入体积" />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="country"
                label="国家/地区"
                rules={[{ required: true, message: '请选择国家/地区' }]}
              >
                <Select 
                  placeholder="请选择国家/地区"
                  onChange={handleCountryChange}
                  defaultValue="CN"
                >
                  {countries.map(country => (
                    <Option key={country.value} value={country.value}>
                      {country.label}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={24}>
              <Form.Item
                name="destination"
                label="目的地"
                rules={[{ required: true, message: '请输入目的地' }]}
              >
                <Input placeholder="请输入详细地址" />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item>
            <Space style={{ width: '100%', justifyContent: 'flex-end' }}>
              <Button onClick={() => form.resetFields()}>
                重置
              </Button>
              <Button type="primary" htmlType="submit" loading={isLoading}>
                <CalculatorOutlined style={{ marginRight: 4 }} />
                计算运费
              </Button>
            </Space>
          </Form.Item>
        </Form>

        {showResults && (
          <>
            <Divider orientation="left">计算结果</Divider>
            <Row gutter={16}>
              {calculationResults.map((result, index) => (
                <Col span={8} key={result.id}>
                  <Card
                    hoverable
                    style={{ marginBottom: 16 }}
                    bodyStyle={{ padding: 16 }}
                    title={
                      <div style={{ display: 'flex', alignItems: 'center' }}>
                        <span style={{ marginRight: 8 }}>{result.icon}</span>
                        <span>{result.name}</span>
                        {index === 0 && <Tag color="green" style={{ marginLeft: 8 }}>推荐</Tag>}
                      </div>
                    }
                  >
                    <Descriptions column={1} size="small">
                      <Descriptions.Item label="预计时效">
                        {result.minDays}-{result.maxDays} 天
                      </Descriptions.Item>
                      <Descriptions.Item label="运费">
                        <Statistic 
                          value={result.convertedCost} 
                          prefix="¥" 
                          precision={2} 
                          valueStyle={{ color: index === 0 ? '#52c41a' : '#1890ff' }}
                        />
                      </Descriptions.Item>
                    </Descriptions>
                  </Card>
                </Col>
              ))}
            </Row>
          </>
        )}

        <Divider orientation="left">计算历史</Divider>
        <Table
          columns={historyColumns}
          dataSource={calculationHistory}
          rowKey="id"
          pagination={{ pageSize: 10 }}
        />
      </Card>
    </div>
  );
};

export default ShippingCostCalculator;