import React, { useState, useEffect } from 'react';
import { Table, Button, Input, Select, DatePicker, message, Modal, Form } from 'antd';
import { EyeOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { useParams } from 'react-router-dom';
import { independentSiteDataSource, SiteOrder } from '@/services/independentSiteDataSource';

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

interface Order {
  id: string;
  orderNumber: string;
  customerName: string;
  total: number;
  status: 'pending' | 'processing' | 'shipped' | 'delivered' | 'cancelled' | 'refunded';
  paymentMethod: string;
  createdAt: string;
  updatedAt: string;
}

const IndependentSiteOrder: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const [orders, setOrders] = useState<Order[]>([]);
  const [loading, setLoading] = useState(false);
  const [filters, setFilters] = useState({
    status: '',
    paymentMethod: '',
    search: '',
    dateRange: null as any,
  });
  const [modalVisible, setModalVisible] = useState(false);
  const [selectedOrder, setSelectedOrder] = useState<Order | null>(null);
  const [form] = Form.useForm();

  useEffect(() => {
    fetchOrders();
  }, [id, filters]);

  const fetchOrders = async () => {
    setLoading(true);
    // 模拟API调用
    setTimeout(() => {
      const mockOrders: Order[] = [
        {
          id: '1',
          orderNumber: 'ORD-2026-001',
          customerName: 'John Doe',
          total: 199.99,
          status: 'processing',
          paymentMethod: 'PayPal',
          createdAt: '2026-03-15',
          updatedAt: '2026-03-16',
        },
        {
          id: '2',
          orderNumber: 'ORD-2026-002',
          customerName: 'Jane Smith',
          total: 299.99,
          status: 'shipped',
          paymentMethod: 'Stripe',
          createdAt: '2026-03-16',
          updatedAt: '2026-03-17',
        },
        {
          id: '3',
          orderNumber: 'ORD-2026-003',
          customerName: 'Bob Johnson',
          total: 99.99,
          status: 'delivered',
          paymentMethod: 'Credit Card',
          createdAt: '2026-03-17',
          updatedAt: '2026-03-18',
        },
        {
          id: '4',
          orderNumber: 'ORD-2026-004',
          customerName: 'Alice Brown',
          total: 499.99,
          status: 'cancelled',
          paymentMethod: 'PayPal',
          createdAt: '2026-03-18',
          updatedAt: '2026-03-18',
        },
      ];
      setOrders(mockOrders);
      setLoading(false);
    }, 500);
  };

  const handleViewOrder = (order: Order) => {
    setSelectedOrder(order);
    form.setFieldsValue(order);
    setModalVisible(true);
  };

  const handleUpdateOrder = async (values: any) => {
    setLoading(true);
    // 模拟API调用
    setTimeout(() => {
      message.success('订单状态更新成功');
      setLoading(false);
      setModalVisible(false);
      fetchOrders();
    }, 1000);
  };

  const handleCancelOrder = (id: string) => {
    message.success('订单已取消');
    fetchOrders();
  };

  const handleRefundOrder = (id: string) => {
    message.success('订单已退款');
    fetchOrders();
  };

  const columns = [
    {
      title: '订单号',
      dataIndex: 'orderNumber',
      key: 'orderNumber',
    },
    {
      title: '客户名称',
      dataIndex: 'customerName',
      key: 'customerName',
    },
    {
      title: '总金额',
      dataIndex: 'total',
      key: 'total',
      render: (total: number) => `$${total.toFixed(2)}`,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => {
        const statusMap = {
          pending: '待处理',
          processing: '处理中',
          shipped: '已发货',
          delivered: '已送达',
          cancelled: '已取消',
          refunded: '已退款',
        };
        return statusMap[status] || status;
      },
    },
    {
      title: '支付方式',
      dataIndex: 'paymentMethod',
      key: 'paymentMethod',
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
    },
    {
      title: '更新时间',
      dataIndex: 'updatedAt',
      key: 'updatedAt',
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: Order) => (
        <div>
          <Button
            type="link"
            icon={<EyeOutlined />}
            onClick={() => handleViewOrder(record)}
          >
            查看
          </Button>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleViewOrder(record)}
          >
            编辑
          </Button>
          {record.status !== 'cancelled' && record.status !== 'refunded' && (
            <>
              <Button
                type="link"
                danger
                onClick={() => handleCancelOrder(record.id)}
              >
                取消
              </Button>
              <Button
                type="link"
                danger
                onClick={() => handleRefundOrder(record.id)}
              >
                退款
              </Button>
            </>
          )}
        </div>
      ),
    },
  ];

  return (
    <div className="independent-site-order">
      <div className="page-header">
        <h1>独立站订单管理</h1>
      </div>

      <div className="filter-section">
        <Search
          placeholder="搜索订单号或客户名称"
          style={{ width: 300, marginRight: 16 }}
          onChange={(e) => setFilters({ ...filters, search: e.target.value })}
        />
        <Select
          placeholder="状态"
          style={{ width: 120, marginRight: 16 }}
          onChange={(value) => setFilters({ ...filters, status: value })}
        >
          <Option value="">全部</Option>
          <Option value="pending">待处理</Option>
          <Option value="processing">处理中</Option>
          <Option value="shipped">已发货</Option>
          <Option value="delivered">已送达</Option>
          <Option value="cancelled">已取消</Option>
          <Option value="refunded">已退款</Option>
        </Select>
        <Select
          placeholder="支付方式"
          style={{ width: 120, marginRight: 16 }}
          onChange={(value) => setFilters({ ...filters, paymentMethod: value })}
        >
          <Option value="">全部</Option>
          <Option value="PayPal">PayPal</Option>
          <Option value="Stripe">Stripe</Option>
          <Option value="Credit Card">信用卡</Option>
          <Option value="Apple Pay">Apple Pay</Option>
        </Select>
        <RangePicker
          style={{ width: 300 }}
          onChange={(dates) => setFilters({ ...filters, dateRange: dates })}
        />
      </div>

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

      {selectedOrder && (
        <Modal
          title={`订单详情 - ${selectedOrder.orderNumber}`}
          open={modalVisible}
          onCancel={() => setModalVisible(false)}
          footer={null}
          width={800}
        >
          <Form
            form={form}
            layout="vertical"
            onFinish={handleUpdateOrder}
          >
            <Form.Item
              name="orderNumber"
              label="订单号"
            >
              <Input disabled />
            </Form.Item>

            <Form.Item
              name="customerName"
              label="客户名称"
            >
              <Input disabled />
            </Form.Item>

            <Form.Item
              name="total"
              label="总金额"
            >
              <Input type="number" disabled />
            </Form.Item>

            <Form.Item
              name="status"
              label="订单状态"
              rules={[{ required: true, message: '请选择订单状态' }]}
            >
              <Select placeholder="请选择订单状态">
                <Option value="pending">待处理</Option>
                <Option value="processing">处理中</Option>
                <Option value="shipped">已发货</Option>
                <Option value="delivered">已送达</Option>
                <Option value="cancelled">已取消</Option>
                <Option value="refunded">已退款</Option>
              </Select>
            </Form.Item>

            <Form.Item
              name="paymentMethod"
              label="支付方式"
            >
              <Input disabled />
            </Form.Item>

            <Form.Item
              name="createdAt"
              label="创建时间"
            >
              <Input disabled />
            </Form.Item>

            <Form.Item
              name="updatedAt"
              label="更新时间"
            >
              <Input disabled />
            </Form.Item>

            <Form.Item
              name="shippingAddress"
              label="收货地址"
            >
              <Input.TextArea rows={3} placeholder="请输入收货地址" />
            </Form.Item>

            <Form.Item
              name="trackingNumber"
              label="物流单号"
            >
              <Input placeholder="请输入物流单号" />
            </Form.Item>

            <Form.Item>
              <Button type="primary" htmlType="submit" loading={loading}>
                更新订单
              </Button>
              <Button style={{ marginLeft: 16 }} onClick={() => setModalVisible(false)}>
                关闭
              </Button>
            </Form.Item>
          </Form>
        </Modal>
      )}
    </div>
  );
};

export default IndependentSiteOrder;