import React, { useState, useEffect } from 'react';
import {
  Card,
  Descriptions,
  Tag,
  Button,
  Space,
  Table,
  Timeline,
  Divider,
  Row,
  Col,
  Statistic,
  Steps,
  message,
  Tabs,
  Tooltip,
  Modal,
  Form,
  Input,
  Select,
} from 'antd';
import {
  ArrowLeftOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  SyncOutlined,
  TruckOutlined,
  ClockCircleOutlined,
  DollarOutlined,
  UserOutlined,
  EnvironmentOutlined,
  EditOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { orderDataSource, OrderDetailData } from '@/services/orderDataSource';

const { TabPane } = Tabs;
const { TextArea } = Input;

// 类型从DataSource导入

const ORDER_STATUS_MAP: Record<string, { color: string; text: string }> = {
  PULLED: { color: 'default', text: 'Pulled' },
  PENDING_REVIEW: { color: 'processing', text: 'Pending Review' },
  CONFIRMED: { color: 'blue', text: 'Confirmed' },
  ALLOCATED: { color: 'cyan', text: 'Allocated' },
  READY_TO_SHIP: { color: 'geekblue', text: 'Ready to Ship' },
  SHIPPED: { color: 'purple', text: 'Shipped' },
  DELIVERED: { color: 'success', text: 'Delivered' },
  CANCELLED: { color: 'error', text: 'Cancelled' },
};

const STATUS_STEPS = [
  { title: 'Pulled', status: 'PULLED' },
  { title: 'Review', status: 'PENDING_REVIEW' },
  { title: 'Confirmed', status: 'CONFIRMED' },
  { title: 'Allocated', status: 'ALLOCATED' },
  { title: 'Ready', status: 'READY_TO_SHIP' },
  { title: 'Shipped', status: 'SHIPPED' },
  { title: 'Delivered', status: 'DELIVERED' },
];

interface OrderDetailProps {
  orderId?: string;
  onBack?: () => void;
}

export const OrderDetail: React.FC<OrderDetailProps> = ({ orderId, onBack }) => {
  const [loading, setLoading] = useState(false);
  const [orderData, setOrderData] = useState<OrderDetailData | null>(null);
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [form] = Form.useForm();

  useEffect(() => {
    if (orderId) {
      fetchOrderDetail(orderId);
    }
  }, [orderId]);

  const fetchOrderDetail = async (id: string) => {
    setLoading(true);
    try {
      const data = await orderDataSource.fetchOrderDetail(id);
      if (data) {
        setOrderData(data);
      }
    } catch (error) {
      message.error('Failed to load order details');
    } finally {
      setLoading(false);
    }
  };

  const handleStatusUpdate = async (newStatus: string) => {
    if (!orderId) return;
    setLoading(true);
    try {
      await orderDataSource.updateStatus(orderId, newStatus);
      message.success('Status updated successfully');
      fetchOrderDetail(orderId);
    } catch (error) {
      message.error('Failed to update status');
    } finally {
      setLoading(false);
    }
  };

  const handleEditAddress = () => {
    if (orderData) {
      form.setFieldsValue(orderData.shippingAddress);
      setEditModalVisible(true);
    }
  };

  const handleSaveAddress = async () => {
    if (!orderId) return;
    try {
      const values = await form.validateFields();
      await orderDataSource.updateAddress(orderId, values);
      message.success('Address updated successfully');
      setEditModalVisible(false);
      fetchOrderDetail(orderId);
    } catch (error) {
      message.error('Failed to save address');
    }
  };

  const getCurrentStep = () => {
    if (!orderData) return 0;
    const index = STATUS_STEPS.findIndex((s) => s.status === orderData.status);
    return index >= 0 ? index : 0;
  };

  const itemColumns: ColumnsType<OrderItem> = [
    { title: 'SKU', dataIndex: 'sku', key: 'sku', width: 100 },
    { title: 'Product', dataIndex: 'productName', key: 'productName' },
    { title: 'Qty', dataIndex: 'quantity', key: 'quantity', width: 60, align: 'center' },
    {
      title: 'Unit Price',
      dataIndex: 'unitPrice',
      key: 'unitPrice',
      width: 100,
      render: (price: number) => `$${price.toFixed(2)}`,
    },
    {
      title: 'Total',
      dataIndex: 'totalPrice',
      key: 'totalPrice',
      width: 100,
      render: (price: number) => <strong>${price.toFixed(2)}</strong>,
    },
    {
      title: 'Status',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: string) => <Tag color="green">{status}</Tag>,
    },
  ];

  if (!orderData) {
    return <Card loading={loading}>Loading...</Card>;
  }

  return (
    <div className="order-detail-page">
      <Card
        title={
          <Space>
            {onBack && (
              <Button icon={<ArrowLeftOutlined />} onClick={onBack}>
                Back
              </Button>
            )}
            <span>Order Details</span>
          </Space>
        }
        extra={
          <Space>
            <Tag color="blue" style={{ fontSize: 14, padding: '4px 12px' }}>
              {orderData.orderId}
            </Tag>
            <Tag color={ORDER_STATUS_MAP[orderData.status].color} style={{ fontSize: 14, padding: '4px 12px' }}>
              {ORDER_STATUS_MAP[orderData.status].text}
            </Tag>
          </Space>
        }
      >
        <Steps
          current={getCurrentStep()}
          status={orderData.status === 'CANCELLED' ? 'error' : 'process'}
          items={STATUS_STEPS.map((s) => ({ title: s.title }))}
          style={{ marginBottom: 24 }}
        />

        <Tabs defaultActiveKey="overview">
          <TabPane tab="Overview" key="overview">
            <Row gutter={24}>
              <Col span={16}>
                <Card title="Order Items" size="small">
                  <Table
                    columns={itemColumns}
                    dataSource={orderData.items}
                    rowKey="id"
                    pagination={false}
                    size="small"
                    summary={() => (
                      <>
                        <Table.Summary.Row>
                          <Table.Summary.Cell index={0} colSpan={4} align="right">Subtotal</Table.Summary.Cell>
                          <Table.Summary.Cell index={1} colSpan={2}>${orderData.subtotal.toFixed(2)}</Table.Summary.Cell>
                        </Table.Summary.Row>
                        <Table.Summary.Row>
                          <Table.Summary.Cell index={0} colSpan={4} align="right">Shipping</Table.Summary.Cell>
                          <Table.Summary.Cell index={1} colSpan={2}>${orderData.shippingFee.toFixed(2)}</Table.Summary.Cell>
                        </Table.Summary.Row>
                        <Table.Summary.Row>
                          <Table.Summary.Cell index={0} colSpan={4} align="right">Tax</Table.Summary.Cell>
                          <Table.Summary.Cell index={1} colSpan={2}>${orderData.tax.toFixed(2)}</Table.Summary.Cell>
                        </Table.Summary.Row>
                        <Table.Summary.Row>
                          <Table.Summary.Cell index={0} colSpan={4} align="right"><strong>Total</strong></Table.Summary.Cell>
                          <Table.Summary.Cell index={1} colSpan={2}>
                            <strong style={{ fontSize: 16, color: '#1890ff' }}>
                              ${orderData.totalAmount.toFixed(2)}
                            </strong>
                          </Table.Summary.Cell>
                        </Table.Summary.Row>
                      </>
                    )}
                  />
                </Card>

                <Card title="Shipping Information" size="small" style={{ marginTop: 16 }} extra={
                  <Button type="link" icon={<EditOutlined />} onClick={handleEditAddress}>Edit</Button>
                }>
                  <Descriptions column={2} size="small">
                    <Descriptions.Item label="Carrier">{orderData.shippingInfo?.carrier || '-'}</Descriptions.Item>
                    <Descriptions.Item label="Tracking #">{orderData.shippingInfo?.trackingNumber || '-'}</Descriptions.Item>
                    <Descriptions.Item label="Shipped At">{orderData.shippingInfo?.shippedAt || '-'}</Descriptions.Item>
                    <Descriptions.Item label="Est. Delivery">{orderData.shippingInfo?.estimatedDelivery || '-'}</Descriptions.Item>
                  </Descriptions>
                </Card>
              </Col>

              <Col span={8}>
                <Card title="Customer" size="small">
                  <p><UserOutlined /> {orderData.customer.name}</p>
                  <p>{orderData.customer.email}</p>
                  <p>{orderData.customer.phone}</p>
                </Card>

                <Card title="Shipping Address" size="small" style={{ marginTop: 16 }}>
                  <p><EnvironmentOutlined /> {orderData.shippingAddress.name}</p>
                  <p>{orderData.shippingAddress.address}</p>
                  <p>{orderData.shippingAddress.city}, {orderData.shippingAddress.state} {orderData.shippingAddress.postalCode}</p>
                  <p>{orderData.shippingAddress.country}</p>
                </Card>

                <Card size="small" style={{ marginTop: 16 }}>
                  <Row gutter={16}>
                    <Col span={12}>
                      <Statistic title="Items" value={orderData.items.length} />
                    </Col>
                    <Col span={12}>
                      <Statistic title="Total Qty" value={orderData.items.reduce((sum, i) => sum + i.quantity, 0)} />
                    </Col>
                  </Row>
                </Card>
              </Col>
            </Row>
          </TabPane>

          <TabPane tab="Timeline" key="timeline">
            <Timeline
              items={orderData.timeline.map((t) => ({
                color: t.status === orderData.status ? 'green' : 'blue',
                children: (
                  <div>
                    <p><strong>{t.description}</strong></p>
                    <p style={{ color: '#666', margin: 0 }}>{t.time}</p>
                  </div>
                ),
              }))}
            />
          </TabPane>

          <TabPane tab="Actions" key="actions">
            <Space direction="vertical" style={{ width: '100%' }}>
              {orderData.status === 'PENDING_REVIEW' && (
                <Card size="small" title="Review Actions">
                  <Space>
                    <Button type="primary" icon={<CheckCircleOutlined />} onClick={() => handleStatusUpdate('CONFIRMED')}>
                      Confirm Order
                    </Button>
                    <Button danger icon={<CloseCircleOutlined />} onClick={() => handleStatusUpdate('CANCELLED')}>
                      Cancel Order
                    </Button>
                  </Space>
                </Card>
              )}
              {orderData.status === 'CONFIRMED' && (
                <Card size="small" title="Fulfillment Actions">
                  <Space>
                    <Button type="primary" onClick={() => handleStatusUpdate('ALLOCATED')}>
                      Allocate Stock
                    </Button>
                  </Space>
                </Card>
              )}
              {orderData.status === 'ALLOCATED' && (
                <Card size="small" title="Shipping Actions">
                  <Space>
                    <Button type="primary" icon={<TruckOutlined />} onClick={() => handleStatusUpdate('READY_TO_SHIP')}>
                      Mark Ready to Ship
                    </Button>
                  </Space>
                </Card>
              )}
              {orderData.status === 'READY_TO_SHIP' && (
                <Card size="small" title="Shipping Actions">
                  <Space>
                    <Button type="primary" icon={<TruckOutlined />} onClick={() => handleStatusUpdate('SHIPPED')}>
                      Mark as Shipped
                    </Button>
                  </Space>
                </Card>
              )}
            </Space>
          </TabPane>
        </Tabs>
      </Card>

      <Modal
        title="Edit Shipping Address"
        open={editModalVisible}
        onCancel={() => setEditModalVisible(false)}
        onOk={handleSaveAddress}
      >
        <Form form={form} layout="vertical">
          <Form.Item name="name" label="Name" rules={[{ required: true }]}>
            <Input />
          </Form.Item>
          <Form.Item name="address" label="Address" rules={[{ required: true }]}>
            <Input />
          </Form.Item>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="city" label="City" rules={[{ required: true }]}>
                <Input />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="state" label="State" rules={[{ required: true }]}>
                <Input />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="postalCode" label="Postal Code" rules={[{ required: true }]}>
                <Input />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="country" label="Country" rules={[{ required: true }]}>
                <Input />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>
    </div>
  );
};

export default OrderDetail;
