import React, { useEffect, useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Card, Descriptions, Tag, Button, Spin, Timeline, Divider, Row, Col } from 'antd';
import { ArrowLeftOutlined } from '@ant-design/icons';
import { getOrderDetail } from '@/api/admin';

const statusMap: Record<string, { color: string; label: string }> = {
  pending_pay: { color: 'gold', label: '待支付' },
  pending_confirm: { color: 'blue', label: '待确认' },
  pending_checkin: { color: 'cyan', label: '待入住' },
  checked_in: { color: 'orange', label: '已入住' },
  completed: { color: 'green', label: '已完成' },
  cancelled: { color: 'default', label: '已取消' },
  refunding: { color: 'red', label: '退款中' },
  refunded: { color: 'purple', label: '已退款' },
};

const OrderDetail: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const [order, setOrder] = useState<any>(null);
  const [loading, setLoading] = useState(false);

  const fetchDetail = async () => {
    setLoading(true);
    try {
      const res: any = await getOrderDetail(Number(id));
      setOrder(res.data);
    } catch (error) {
      console.error('加载订单详情失败:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (id) fetchDetail();
  }, [id]);

  if (loading) {
    return (
      <div style={{ textAlign: 'center', padding: '100px 0' }}>
        <Spin size="large" />
      </div>
    );
  }

  if (!order) return null;

  return (
    <div>
      <Button icon={<ArrowLeftOutlined />} onClick={() => navigate(-1)} style={{ marginBottom: 16 }}>
        返回
      </Button>

      <Card title="订单信息" style={{ marginBottom: 16 }}>
        <Descriptions column={2} bordered>
          <Descriptions.Item label="订单号">{order.orderNo}</Descriptions.Item>
          <Descriptions.Item label="订单状态">
            <Tag color={statusMap[order.status]?.color}>{statusMap[order.status]?.label}</Tag>
          </Descriptions.Item>
          <Descriptions.Item label="用户">{order.user?.nickname || '-'}</Descriptions.Item>
          <Descriptions.Item label="用户手机">{order.user?.phone || '-'}</Descriptions.Item>
          <Descriptions.Item label="商家">{order.merchant?.shopName || '-'}</Descriptions.Item>
          <Descriptions.Item label="商家手机">{order.merchant?.phone || '-'}</Descriptions.Item>
          <Descriptions.Item label="房源名称">{order.room?.name || '-'}</Descriptions.Item>
          <Descriptions.Item label="房源地址">{order.room?.address || '-'}</Descriptions.Item>
          <Descriptions.Item label="入住日期">{order.checkInDate}</Descriptions.Item>
          <Descriptions.Item label="离店日期">{order.checkOutDate}</Descriptions.Item>
          <Descriptions.Item label="入住天数">{order.nights}晚</Descriptions.Item>
          <Descriptions.Item label="入住人数">{order.guestCount}人</Descriptions.Item>
        </Descriptions>
      </Card>

      <Row gutter={16} style={{ marginBottom: 16 }}>
        <Col span={12}>
          <Card title="价格明细">
            <Descriptions column={1} bordered>
              <Descriptions.Item label="房费">¥{order.roomPrice}</Descriptions.Item>
              <Descriptions.Item label="优惠金额">-¥{order.discountAmount || 0}</Descriptions.Item>
              <Descriptions.Item label="实付金额">
                <span style={{ color: '#ff4d4f', fontSize: 18, fontWeight: 'bold' }}>
                  ¥{order.payAmount}
                </span>
              </Descriptions.Item>
              <Descriptions.Item label="平台服务费">¥{order.platformFee || 0}</Descriptions.Item>
              <Descriptions.Item label="商家实收">¥{order.merchantAmount || 0}</Descriptions.Item>
            </Descriptions>
          </Card>
        </Col>

        <Col span={12}>
          <Card title="支付信息">
            <Descriptions column={1} bordered>
              <Descriptions.Item label="支付方式">
                {order.paymentMethod === 'wechat' ? '微信支付' : order.paymentMethod === 'alipay' ? '支付宝' : '-'}
              </Descriptions.Item>
              <Descriptions.Item label="支付时间">{order.paidAt || '-'}</Descriptions.Item>
              <Descriptions.Item label="交易号">{order.transactionId || '-'}</Descriptions.Item>
              {order.status === 'refunded' && (
                <>
                  <Descriptions.Item label="退款金额">¥{order.refundAmount || order.payAmount}</Descriptions.Item>
                  <Descriptions.Item label="退款时间">{order.refundedAt || '-'}</Descriptions.Item>
                  <Descriptions.Item label="退款原因">{order.cancelReason || '-'}</Descriptions.Item>
                </>
              )}
            </Descriptions>
          </Card>
        </Col>
      </Row>

      {order.contactName && (
        <Card title="联系信息" style={{ marginBottom: 16 }}>
          <Descriptions column={2} bordered>
            <Descriptions.Item label="联系人">{order.contactName}</Descriptions.Item>
            <Descriptions.Item label="联系电话">{order.contactPhone}</Descriptions.Item>
            <Descriptions.Item label="备注" span={2}>{order.remark || '-'}</Descriptions.Item>
          </Descriptions>
        </Card>
      )}

      <Card title="订单时间线">
        <Timeline>
          <Timeline.Item color="green">
            订单创建：{order.createdAt}
          </Timeline.Item>
          {order.paidAt && (
            <Timeline.Item color="blue">
              支付完成：{order.paidAt}
            </Timeline.Item>
          )}
          {order.confirmedAt && (
            <Timeline.Item color="cyan">
              商家确认：{order.confirmedAt}
            </Timeline.Item>
          )}
          {order.checkedInAt && (
            <Timeline.Item color="orange">
              办理入住：{order.checkedInAt}
            </Timeline.Item>
          )}
          {order.checkedOutAt && (
            <Timeline.Item color="purple">
              办理退房：{order.checkedOutAt}
            </Timeline.Item>
          )}
          {order.completedAt && (
            <Timeline.Item color="green">
              订单完成：{order.completedAt}
            </Timeline.Item>
          )}
          {order.cancelledAt && (
            <Timeline.Item color="red">
              订单取消：{order.cancelledAt}
              {order.cancelReason && <div>取消原因：{order.cancelReason}</div>}
            </Timeline.Item>
          )}
          {order.refundedAt && (
            <Timeline.Item color="red">
              退款完成：{order.refundedAt}
            </Timeline.Item>
          )}
        </Timeline>
      </Card>
    </div>
  );
};

export default OrderDetail;
