import React, { useState, useEffect } from 'react';
import { Card, Table, Button, Select, DatePicker, Space, Modal, Tabs, Descriptions, Badge, message, Spin, Input } from 'antd';
import { EyeOutlined, CheckOutlined, CloseOutlined, DownloadOutlined, UploadOutlined, PlusOutlined } from '@ant-design/icons';
import { orderApi } from '../services/ApiService';

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

const OrdersPage: React.FC = () => {
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [isDetailModalVisible, setIsDetailModalVisible] = useState(false);
  const [isProcessModalVisible, setIsProcessModalVisible] = useState(false);
  const [selectedOrder, setSelectedOrder] = useState<any>(null);
  const [isProcessing, setIsProcessing] = useState(false);
  const [orderStatus, setOrderStatus] = useState<string>('');
  const [orders, setOrders] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [totalOrders, setTotalOrders] = useState(0);
  const [pendingOrders, setPendingOrders] = useState(0);
  const [shippedOrders, setShippedOrders] = useState(0);
  const [deliveredOrders, setDeliveredOrders] = useState(0);
  const [refundedOrders, setRefundedOrders] = useState(0);

  // 加载订单数据
  useEffect(() => {
    loadOrders();
  }, []);

  const loadOrders = async () => {
    setLoading(true);
    try {
      const response = await orderApi.getOrders();
      setOrders(response.data || []);
      calculateStatistics(response.data || []);
    } catch (error) {
      console.error('Failed to load orders:', error);
      message.error('Failed to load orders');
      // 加载失败时使用mock数据
      const mockOrders = [
        {
          id: '1001',
          orderNo: 'ORD-2026-0001',
          customer: 'John Doe',
          total: 259.98,
          status: 'pending',
          platform: 'Amazon',
          date: '2026-03-18',
          items: [
            { name: 'Wireless Headphones', quantity: 2, price: 129.99 },
          ],
        },
        {
          id: '1002',
          orderNo: 'ORD-2026-0002',
          customer: 'Jane Smith',
          total: 89.99,
          status: 'shipped',
          platform: 'eBay',
          date: '2026-03-17',
          items: [
            { name: 'Bluetooth Speaker', quantity: 1, price: 89.99 },
          ],
        },
        {
          id: '1003',
          orderNo: 'ORD-2026-0003',
          customer: 'Bob Johnson',
          total: 199.99,
          status: 'delivered',
          platform: 'Shopee',
          date: '2026-03-16',
          items: [
            { name: 'Smart Watch', quantity: 1, price: 199.99 },
          ],
        },
        {
          id: '1004',
          orderNo: 'ORD-2026-0004',
          customer: 'Alice Williams',
          total: 69.99,
          status: 'refunded',
          platform: 'Amazon',
          date: '2026-03-15',
          items: [
            { name: 'Fitness Tracker', quantity: 1, price: 69.99 },
          ],
        },
      ];
      setOrders(mockOrders);
      calculateStatistics(mockOrders);
    } finally {
      setLoading(false);
    }
  };

  const calculateStatistics = (orderList: any[]) => {
    if (!orderList || orderList.length === 0) {
      setTotalOrders(0);
      setPendingOrders(0);
      setShippedOrders(0);
      setDeliveredOrders(0);
      setRefundedOrders(0);
      return;
    }

    const total = orderList.length;
    const pending = orderList.filter(order => order.status === 'pending').length;
    const shipped = orderList.filter(order => order.status === 'shipped').length;
    const delivered = orderList.filter(order => order.status === 'delivered').length;
    const refunded = orderList.filter(order => order.status === 'refunded').length;

    setTotalOrders(total);
    setPendingOrders(pending);
    setShippedOrders(shipped);
    setDeliveredOrders(delivered);
    setRefundedOrders(refunded);
  };

  const handleViewDetail = async (record: any) => {
    try {
      const response = await orderApi.getOrder(record.id);
      setSelectedOrder(response.data || record);
      setIsDetailModalVisible(true);
    } catch (error) {
      console.error('Failed to get order detail:', error);
      setSelectedOrder(record);
      setIsDetailModalVisible(true);
    }
  };

  const handleProcessOrder = (record: any) => {
    setSelectedOrder(record);
    setOrderStatus(record.status);
    setIsProcessModalVisible(true);
  };

  const handleRefundOrder = async (record: any) => {
    try {
      await orderApi.updateStatus(record.id, 'refunded');
      message.success(`Refund process initiated for order ${record.orderNo}`);
      // 重新加载订单数据
      loadOrders();
    } catch (error) {
      console.error('Failed to refund order:', error);
      message.error('Failed to refund order');
    }
  };

  const handleBatchShip = async () => {
    if (selectedRowKeys.length === 0) return;
    
    try {
      // 批量发货
      for (const key of selectedRowKeys) {
        await orderApi.updateStatus(key.toString(), 'shipped');
      }
      message.success('Batch shipping initiated');
      // 重新加载订单数据
      loadOrders();
    } catch (error) {
      console.error('Failed to batch ship:', error);
      message.error('Failed to batch ship');
    }
  };

  const handleBatchCancel = async () => {
    if (selectedRowKeys.length === 0) return;
    
    try {
      // 批量取消
      for (const key of selectedRowKeys) {
        await orderApi.updateStatus(key.toString(), 'cancelled');
      }
      message.success('Batch cancellation initiated');
      // 重新加载订单数据
      loadOrders();
    } catch (error) {
      console.error('Failed to batch cancel:', error);
      message.error('Failed to batch cancel');
    }
  };

  const handleBatchExport = async () => {
    if (selectedRowKeys.length === 0) return;
    
    try {
      // 调用导出API
      await orderApi.getOrders({ export: true, ids: selectedRowKeys });
      message.success('Orders exported');
    } catch (error) {
      console.error('Failed to batch export:', error);
      message.error('Failed to batch export');
    }
  };

  const handleCreateOrder = () => {
    // 这里可以打开创建订单的表单
    message.success('Create order form opened');
  };

  const handleImportOrders = () => {
    // 这里可以打开导入订单的对话框
    message.success('Import orders dialog opened');
  };

  const handleExportOrders = async () => {
    try {
      // 调用导出API
      await orderApi.getOrders({ export: true });
      message.success('Orders exported');
    } catch (error) {
      console.error('Failed to export orders:', error);
      message.error('Failed to export orders');
    }
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'pending': return 'blue';
      case 'shipped': return 'green';
      case 'delivered': return 'green';
      case 'refunded': return 'red';
      case 'cancelled': return 'red';
      default: return 'default';
    }
  };

  const columns = [
    {
      title: 'Order No',
      dataIndex: 'orderNo',
      key: 'orderNo',
    },
    {
      title: 'Customer',
      dataIndex: 'customer',
      key: 'customer',
    },
    {
      title: 'Total',
      dataIndex: 'total',
      key: 'total',
      render: (value: number) => `¥${value}`,
    },
    {
      title: 'Status',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => (
        <Badge status={getStatusColor(status)} text={status} />
      ),
    },
    {
      title: 'Platform',
      dataIndex: 'platform',
      key: 'platform',
    },
    {
      title: 'Date',
      dataIndex: 'date',
      key: 'date',
    },
    {
      title: 'Actions',
      key: 'actions',
      render: (_: any, record: any) => (
        <Space size="middle">
          <Button icon={<EyeOutlined />} onClick={() => handleViewDetail(record)}>View</Button>
          <Button onClick={() => handleProcessOrder(record)}>Process</Button>
          <Button onClick={() => handleRefundOrder(record)}>Refund</Button>
        </Space>
      ),
    },
  ];

  const rowSelection = {
    selectedRowKeys,
    onChange: (keys: React.Key[]) => {
      setSelectedRowKeys(keys);
    },
  };

  return (
    <div className="orders-page">
      <div className="page-header" style={{ marginBottom: 24, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <h1>Orders</h1>
        <Space>
          <Button icon={<PlusOutlined />} onClick={handleCreateOrder}>Create Order</Button>
          <Button icon={<UploadOutlined />} onClick={handleImportOrders}>Import Orders</Button>
          <Button icon={<DownloadOutlined />} onClick={handleExportOrders}>Export Data</Button>
        </Space>
      </div>

      <Card style={{ marginBottom: 24 }}>
        <div style={{ display: 'flex', gap: 16, marginBottom: 16, flexWrap: 'wrap' }}>
          <Select placeholder="Select Status" style={{ width: 150 }}>
            <Option value="all">All Status</Option>
            <Option value="pending">Pending</Option>
            <Option value="shipped">Shipped</Option>
            <Option value="delivered">Delivered</Option>
            <Option value="refunded">Refunded</Option>
            <Option value="cancelled">Cancelled</Option>
          </Select>
          <Select placeholder="Select Platform" style={{ width: 150 }}>
            <Option value="all">All Platforms</Option>
            <Option value="amazon">Amazon</Option>
            <Option value="ebay">eBay</Option>
            <Option value="shopee">Shopee</Option>
          </Select>
          <RangePicker style={{ width: 300 }} />
        </div>

        <div style={{ marginBottom: 16 }}>
          <Space>
            <Button onClick={handleBatchShip} disabled={selectedRowKeys.length === 0}>
              Batch Ship
            </Button>
            <Button onClick={handleBatchCancel} disabled={selectedRowKeys.length === 0}>
              Batch Cancel
            </Button>
            <Button onClick={handleBatchExport} disabled={selectedRowKeys.length === 0}>
              Batch Export
            </Button>
          </Space>
        </div>

        <Table
          rowSelection={rowSelection}
          columns={columns}
          dataSource={orders}
          rowKey="id"
          loading={loading}
          pagination={{
            pageSize: 10,
          }}
        />
      </Card>

      <Card title="Order Statistics" style={{ marginBottom: 24 }}>
        <div style={{ display: 'flex', justifyContent: 'space-around' }}>
          <div style={{ textAlign: 'center' }}>
            <h3>Total Orders</h3>
            <p style={{ fontSize: '24px', fontWeight: 'bold' }}>{totalOrders}</p>
          </div>
          <div style={{ textAlign: 'center' }}>
            <h3>Pending</h3>
            <p style={{ fontSize: '24px', fontWeight: 'bold', color: '#1890ff' }}>{pendingOrders}</p>
          </div>
          <div style={{ textAlign: 'center' }}>
            <h3>Shipped</h3>
            <p style={{ fontSize: '24px', fontWeight: 'bold', color: '#52c41a' }}>{shippedOrders}</p>
          </div>
          <div style={{ textAlign: 'center' }}>
            <h3>Delivered</h3>
            <p style={{ fontSize: '24px', fontWeight: 'bold', color: '#52c41a' }}>{deliveredOrders}</p>
          </div>
          <div style={{ textAlign: 'center' }}>
            <h3>Refunded</h3>
            <p style={{ fontSize: '24px', fontWeight: 'bold', color: '#f5222d' }}>{refundedOrders}</p>
          </div>
        </div>
      </Card>

      <Modal
        title={`Order Detail - ${selectedOrder?.orderNo}`}
        open={isDetailModalVisible}
        onCancel={() => setIsDetailModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setIsDetailModalVisible(false)}>
            Close
          </Button>,
        ]}
        width={800}
      >
        {selectedOrder && (
          <Tabs defaultActiveKey="details">
            <TabPane tab="Order Details" key="details">
              <Descriptions column={2}>
                <Descriptions.Item label="Order No">{selectedOrder.orderNo}</Descriptions.Item>
                <Descriptions.Item label="Customer">{selectedOrder.customer}</Descriptions.Item>
                <Descriptions.Item label="Total">¥{selectedOrder.total}</Descriptions.Item>
                <Descriptions.Item label="Status">
                  <Badge status={getStatusColor(selectedOrder.status)} text={selectedOrder.status} />
                </Descriptions.Item>
                <Descriptions.Item label="Platform">{selectedOrder.platform}</Descriptions.Item>
                <Descriptions.Item label="Date">{selectedOrder.date}</Descriptions.Item>
              </Descriptions>
              <h3 style={{ marginTop: 24 }}>Items</h3>
              <Table
                columns={[
                  { title: 'Product', dataIndex: 'name', key: 'name' },
                  { title: 'Quantity', dataIndex: 'quantity', key: 'quantity' },
                  { title: 'Price', dataIndex: 'price', key: 'price', render: (value: number) => `¥${value}` },
                ]}
                dataSource={selectedOrder.items}
                rowKey="name"
                pagination={false}
              />
            </TabPane>
            <TabPane tab="Shipping" key="shipping">
              <p>Shipping information will be displayed here</p>
            </TabPane>
            <TabPane tab="Payment" key="payment">
              <p>Payment information will be displayed here</p>
            </TabPane>
          </Tabs>
        )}
      </Modal>

      <Modal
        title={`Process Order - ${selectedOrder?.orderNo}`}
        open={isProcessModalVisible}
        onCancel={() => setIsProcessModalVisible(false)}
        onOk={async () => {
          setIsProcessing(true);
          
          try {
            await orderApi.updateStatus(selectedOrder.id, orderStatus);
            setIsProcessing(false);
            setIsProcessModalVisible(false);
            message.success('Order processed successfully');
            // 重新加载订单数据
            loadOrders();
          } catch (error) {
            console.error('Failed to process order:', error);
            setIsProcessing(false);
            message.error('Failed to process order');
          }
        }}
      >
        {isProcessing ? (
          <div style={{ display: 'flex', justifyContent: 'center', padding: '40px 0' }}>
            <div>
              <p>Processing order...</p>
              <div style={{ marginTop: 16, display: 'flex', justifyContent: 'center' }}>
                <Spin size="large" />
              </div>
            </div>
          </div>
        ) : (
          <>
            <div style={{ margin: '16px 0' }}>
              <p>Order: {selectedOrder?.orderNo}</p>
              <p>Customer: {selectedOrder?.customer}</p>
              <p>Current Status: <Badge status={getStatusColor(selectedOrder?.status || '')} text={selectedOrder?.status} /></p>
            </div>
            <div style={{ margin: '16px 0' }}>
              <h3>Update Status</h3>
              <Select 
                style={{ width: '100%' }} 
                defaultValue={selectedOrder?.status}
                onChange={(value) => setOrderStatus(value)}
              >
                <Option value="pending">Pending</Option>
                <Option value="shipped">Shipped</Option>
                <Option value="delivered">Delivered</Option>
                <Option value="cancelled">Cancelled</Option>
              </Select>
            </div>
            {orderStatus === 'shipped' && (
              <div style={{ margin: '16px 0' }}>
                <h3>Shipping Information</h3>
                <Input placeholder="Tracking Number" style={{ marginBottom: 8 }} />
                <Select style={{ width: '100%' }} placeholder="Shipping Carrier">
                  <Option value="fedex">FedEx</Option>
                  <Option value="ups">UPS</Option>
                  <Option value="usps">USPS</Option>
                  <Option value="dhl">DHL</Option>
                </Select>
              </div>
            )}
          </>
        )}
      </Modal>
    </div>
  );
};

export default OrdersPage;