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

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

// 模拟订单数据
const mockOrders = [
  {
    id: 'ORD-20260318-001',
    customerName: '张三',
    productName: 'Apple iPhone 15 Pro',
    quantity: 1,
    weight: 0.5,
    volume: 0.01,
    destination: '北京市朝阳区',
    status: 'PENDING',
  },
  {
    id: 'ORD-20260318-002',
    customerName: '李四',
    productName: 'MacBook Pro 14',
    quantity: 1,
    weight: 2.0,
    volume: 0.05,
    destination: '上海市浦东新区',
    status: 'PENDING',
  },
  {
    id: 'ORD-20260318-003',
    customerName: '王五',
    productName: 'AirPods Pro 2',
    quantity: 2,
    weight: 0.2,
    volume: 0.005,
    destination: '广州市天河区',
    status: 'PENDING',
  },
];

// 模拟物流选项
const mockLogisticsOptions = [
  {
    id: 'LOG-001',
    name: '顺丰速运',
    type: 'EXPRESS',
    icon: <TruckOutlined />,
    estimatedDays: 1-2,
    cost: 23.00,
    reliability: 98,
    features: ['次日达', '上门取件', '保价服务'],
  },
  {
    id: 'LOG-002',
    name: '中通快递',
    type: 'STANDARD',
    icon: <TruckOutlined />,
    estimatedDays: 2-3,
    cost: 12.00,
    reliability: 95,
    features: ['上门取件', '短信通知'],
  },
  {
    id: 'LOG-003',
    name: 'EMS',
    type: 'EXPRESS',
    icon: <PlaneOutlined />,
    estimatedDays: 1-2,
    cost: 25.00,
    reliability: 99,
    features: ['次日达', '上门取件', '全球配送'],
  },
  {
    id: 'LOG-004',
    name: '韵达快递',
    type: 'STANDARD',
    icon: <TruckOutlined />,
    estimatedDays: 3-4,
    cost: 10.00,
    reliability: 90,
    features: ['上门取件'],
  },
];

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

const LogisticsSelect: React.FC = () => {
  const [form] = Form.useForm();
  const [orders, setOrders] = useState(mockOrders);
  const [selectedOrder, setSelectedOrder] = useState<any>(null);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [logisticsOptions, setLogisticsOptions] = useState(mockLogisticsOptions);
  const [selectedOption, setSelectedOption] = useState<string>('');
  const [showResults, setShowResults] = useState(false);

  // 处理订单选择
  const handleOrderSelect = (order: any) => {
    setSelectedOrder(order);
    form.setFieldsValue({
      orderId: order.id,
      productName: order.productName,
      quantity: order.quantity,
      weight: order.weight,
      volume: order.volume,
      destination: order.destination,
    });
    setIsModalVisible(true);
  };

  // 处理物流选项查询
  const handleQuery = async (values: any) => {
    setIsLoading(true);
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      // 根据目的地和重量过滤物流选项
      const filteredOptions = mockLogisticsOptions.map(option => {
        // 模拟根据重量计算价格
        const calculatedCost = option.cost * (values.weight || 1);
        return {
          ...option,
          cost: calculatedCost,
        };
      });
      
      setLogisticsOptions(filteredOptions);
      setShowResults(true);
      message.success('物流选项查询成功');
    } catch (error) {
      message.error('物流选项查询失败');
    } finally {
      setIsLoading(false);
    }
  };

  // 处理物流方式选择
  const handleSelect = async (optionId: string) => {
    setIsLoading(true);
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      setSelectedOption(optionId);
      message.success('物流方式选择成功');
      
      // 更新订单状态
      const updatedOrders = orders.map(order => {
        if (order.id === selectedOrder.id) {
          return {
            ...order,
            status: 'SHIPPING',
          };
        }
        return order;
      });
      
      setOrders(updatedOrders);
      setIsModalVisible(false);
      form.resetFields();
      setShowResults(false);
    } catch (error) {
      message.error('物流方式选择失败');
    } finally {
      setIsLoading(false);
    }
  };

  // 物流类型标签
  const getTypeTag = (type: string) => {
    switch (type) {
      case 'EXPRESS':
        return <Tag color="red">快递</Tag>;
      case 'STANDARD':
        return <Tag color="blue">标准</Tag>;
      case 'ECONOMY':
        return <Tag color="green">经济</Tag>;
      default:
        return <Tag>{type}</Tag>;
    }
  };

  // 订单状态标签
  const getStatusTag = (status: string) => {
    switch (status) {
      case 'PENDING':
        return <Tag color="processing">待处理</Tag>;
      case 'SHIPPING':
        return <Tag color="success">已发货</Tag>;
      case 'DELIVERED':
        return <Tag color="success">已送达</Tag>;
      default:
        return <Tag>{status}</Tag>;
    }
  };

  // 订单表格列
  const orderColumns = [
    {
      title: '订单ID',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '客户姓名',
      dataIndex: 'customerName',
      key: 'customerName',
    },
    {
      title: '商品名称',
      dataIndex: 'productName',
      key: 'productName',
    },
    {
      title: '数量',
      dataIndex: 'quantity',
      key: 'quantity',
    },
    {
      title: '重量(kg)',
      dataIndex: 'weight',
      key: 'weight',
    },
    {
      title: '目的地',
      dataIndex: 'destination',
      key: 'destination',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => getStatusTag(status),
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: any) => (
        <Button type="primary" onClick={() => handleOrderSelect(record)}>
          选择物流
        </Button>
      ),
    },
  ];

  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>
        <Table
          columns={orderColumns}
          dataSource={orders}
          rowKey="id"
          pagination={{ pageSize: 10 }}
        />
      </Card>

      {/* 物流选择模态框 */}
      <Modal
        title="选择物流方式"
        open={isModalVisible}
        onCancel={() => setIsModalVisible(false)}
        footer={null}
        width={1000}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleQuery}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="orderId"
                label="订单ID"
                rules={[{ required: true, message: '请选择订单' }]}
              >
                <Input disabled />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="productName"
                label="商品名称"
                rules={[{ required: true, message: '商品名称不能为空' }]}
              >
                <Input disabled />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={8}>
              <Form.Item
                name="quantity"
                label="数量"
                rules={[{ required: true, message: '数量不能为空' }]}
              >
                <Input type="number" disabled />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="weight"
                label="重量(kg)"
                rules={[{ required: true, message: '重量不能为空' }]}
              >
                <Input type="number" step="0.1" />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="volume"
                label="体积(m³)"
                rules={[{ required: true, message: '体积不能为空' }]}
              >
                <Input type="number" step="0.001" />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="country"
                label="国家/地区"
                rules={[{ required: true, message: '请选择国家/地区' }]}
              >
                <Select placeholder="请选择国家/地区">
                  {countries.map(country => (
                    <Option key={country.value} value={country.value}>
                      {country.label}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="destination"
                label="目的地"
                rules={[{ required: true, message: '请输入目的地' }]}
              >
                <Input />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="logisticsType"
            label="物流类型"
            rules={[{ required: true, message: '请选择物流类型' }]}
          >
            <Radio.Group>
              <Radio value="EXPRESS">快递</Radio>
              <Radio value="STANDARD">标准</Radio>
              <Radio value="ECONOMY">经济</Radio>
            </Radio.Group>
          </Form.Item>

          <Form.Item>
            <Space style={{ width: '100%', justifyContent: 'flex-end' }}>
              <Button onClick={() => setIsModalVisible(false)}>
                取消
              </Button>
              <Button type="primary" htmlType="submit" loading={isLoading}>
                查询物流选项
              </Button>
            </Space>
          </Form.Item>
        </Form>

        {showResults && (
          <>
            <Divider orientation="left">物流选项</Divider>
            <Row gutter={16}>
              {logisticsOptions.map(option => (
                <Col span={12} key={option.id}>
                  <Card
                    hoverable
                    style={{ marginBottom: 16 }}
                    bordered={selectedOption === option.id}
                    bodyStyle={{ padding: 16 }}
                  >
                    <div style={{ display: 'flex', alignItems: 'center', marginBottom: 12 }}>
                      <div style={{ marginRight: 12, fontSize: 24 }}>
                        {option.icon}
                      </div>
                      <div>
                        <div style={{ fontWeight: 'bold', fontSize: 16 }}>{option.name}</div>
                        {getTypeTag(option.type)}
                      </div>
                    </div>
                    
                    <Descriptions column={2} size="small">
                      <Descriptions.Item label="预计时效">
                        <ClockCircleOutlined style={{ marginRight: 4 }} />
                        {option.estimatedDays} 天
                      </Descriptions.Item>
                      <Descriptions.Item label="运费">
                        <DollarOutlined style={{ marginRight: 4 }} />
                        ¥{option.cost.toFixed(2)}
                      </Descriptions.Item>
                      <Descriptions.Item label="可靠性">
                        {option.reliability}%
                      </Descriptions.Item>
                      <Descriptions.Item label="特色服务">
                        {option.features.join(', ')}
                      </Descriptions.Item>
                    </Descriptions>
                    
                    <Button
                      type={selectedOption === option.id ? 'primary' : 'default'}
                      style={{ marginTop: 16, width: '100%' }}
                      onClick={() => handleSelect(option.id)}
                      loading={isLoading}
                    >
                      {selectedOption === option.id ? (
                        <>
                          <CheckCircleOutlined style={{ marginRight: 4 }} />
                          已选择
                        </>
                      ) : (
                        '选择'
                      )}
                    </Button>
                  </Card>
                </Col>
              ))}
            </Row>
          </>
        )}
      </Modal>
    </div>
  );
};

export default LogisticsSelect;