import {
  useState,
  useEffect,
  useParams,
  Table,
  Button,
  Input,
  Select,
  DatePicker,
  message,
  Modal,
  Form,
  EyeOutlined,
  EditOutlined,
  DeleteOutlined,
  Option,
  RangePicker,
  Search,
  FC,
} from '@/imports';
import { independentSiteDataSource, SiteOrder } from '@/services/independentSiteDataSource';

const IndependentSiteOrder: FC = () => {
  const { id } = useParams<{ id: string }>();
  const [orders, setOrders] = useState<SiteOrder[]>([]);
  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<SiteOrder | null>(null);
  const [form] = Form.useForm();

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

  const fetchOrders = async () => {
    setLoading(true);
    setTimeout(() => {
      const mockOrders: SiteOrder[] = [
        {
          id: '1',
          siteId: id || '',
          orderNumber: 'ORD-2026-001',
          customerName: 'John Doe',
          customerEmail: 'john@example.com',
          total: 199.99,
          currency: 'USD',
          status: 'processing',
          paymentMethod: 'PayPal',
          paymentStatus: 'paid',
          shippingAddress: {
            name: 'John Doe',
            address: '123 Main St',
            city: 'New York',
            country: 'USA',
            zipCode: '10001'
          },
          items: [],
          createdAt: '2026-03-15',
          updatedAt: '2026-03-16',
        },
        {
          id: '2',
          siteId: id || '',
          orderNumber: 'ORD-2026-002',
          customerName: 'Jane Smith',
          customerEmail: 'jane@example.com',
          total: 299.99,
          currency: 'USD',
          status: 'shipped',
          paymentMethod: 'Stripe',
          paymentStatus: 'paid',
          shippingAddress: {
            name: 'Jane Smith',
            address: '456 Oak Ave',
            city: 'Los Angeles',
            country: 'USA',
            zipCode: '90001'
          },
          items: [],
          createdAt: '2026-03-16',
          updatedAt: '2026-03-17',
        },
        {
          id: '3',
          siteId: id || '',
          orderNumber: 'ORD-2026-003',
          customerName: 'Bob Johnson',
          customerEmail: 'bob@example.com',
          total: 149.99,
          currency: 'USD',
          status: 'pending',
          paymentMethod: 'Credit Card',
          paymentStatus: 'pending',
          shippingAddress: {
            name: 'Bob Johnson',
            address: '789 Pine Rd',
            city: 'Chicago',
            country: 'USA',
            zipCode: '60601'
          },
          items: [],
          createdAt: '2026-03-17',
          updatedAt: '2026-03-17',
        },
      ];
      setOrders(mockOrders);
      setLoading(false);
    }, 500);
  };

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

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

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

  const handleRefundOrder = (orderId: 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: Record<string, string> = {
          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: SiteOrder) => (
        <div>
          <Button
            type="link"
            icon={<EyeOutlined />}
            onClick={() => handleViewOrder(record)}
          >
            查看
          </Button>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleViewOrder(record)}
          >
            编辑
          </Button>
        </div>
      ),
    },
  ];

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

      <div className="filters">
        <Search
          placeholder="搜索订单号或客户名称"
          style={{ width: 300, marginBottom: 16 }}
          onSearch={(value) => setFilters({ ...filters, search: value })}
        />
        <Select
          placeholder="订单状态"
          style={{ width: 150, marginLeft: 8 }}
          onChange={(value) => setFilters({ ...filters, status: value })}
          allowClear
        >
          <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: 150, marginLeft: 8 }}
          onChange={(value) => setFilters({ ...filters, paymentMethod: value })}
          allowClear
        >
          <Option value="PayPal">PayPal</Option>
          <Option value="Stripe">Stripe</Option>
          <Option value="Credit Card">信用卡</Option>
        </Select>
        <RangePicker
          style={{ marginLeft: 8 }}
          onChange={(dates) => setFilters({ ...filters, dateRange: dates })}
        />
      </div>

      <Table
        columns={columns}
        dataSource={orders}
        rowKey="id"
        loading={loading}
      />

      <Modal
        title="订单详情"
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        onOk={() => form.submit()}
      >
        <Form form={form} onFinish={handleUpdateOrder} layout="vertical">
          <Form.Item name="orderNumber" label="订单号">
            <Input disabled />
          </Form.Item>
          <Form.Item name="customerName" label="客户名称">
            <Input disabled />
          </Form.Item>
          <Form.Item name="total" label="总金额">
            <Input disabled />
          </Form.Item>
          <Form.Item name="status" label="状态">
            <Select>
              <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>
      </Modal>
    </div>
  );
};

export default IndependentSiteOrder;
