import React, { useEffect, useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Card, Descriptions, Tag, Button, Space, Modal, Input, message, Spin, Timeline, Divider } from 'antd';
import { ArrowLeftOutlined } from '@ant-design/icons';
import { getOrderDetail, confirmOrder, rejectOrder, checkinOrder, checkoutOrder } from '@/api/order';

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 { orderNo } = useParams<{ orderNo: string }>();
  const navigate = useNavigate();
  const [order, setOrder] = useState<any>(null);
  const [loading, setLoading] = useState(false);
  const [rejectModal, setRejectModal] = useState<{ visible: boolean; reason: string }>({ visible: false, reason: '' });

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

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

  const handleConfirm = async () => {
    try {
      await confirmOrder(orderNo!);
      message.success('已确认订单');
      fetchDetail();
    } catch (error) {
      message.error('确认失败');
    }
  };

  const handleReject = async () => {
    if (!rejectModal.reason) {
      message.warning('请填写拒绝原因');
      return;
    }
    try {
      await rejectOrder(orderNo!, rejectModal.reason);
      message.success('已拒绝订单');
      setRejectModal({ visible: false, reason: '' });
      fetchDetail();
    } catch (error) {
      message.error('拒绝失败');
    }
  };

  const handleCheckin = async () => {
    try {
      await checkinOrder(orderNo!);
      message.success('已办理入住');
      fetchDetail();
    } catch (error) {
      message.error('办理入住失败');
    }
  };

  const handleCheckout = async () => {
    Modal.confirm({
      title: '确认离店',
      content: '确认客人已离店？订单将标记为已完成',
      onOk: async () => {
        try {
          await checkoutOrder(orderNo!);
          message.success('已确认离店');
          fetchDetail();
        } catch (error) {
          message.error('确认离店失败');
        }
      },
    });
  };

  const canCheckout = () => {
    if (!order || order.status !== 'checked_in') return false;
    const today = new Date().toISOString().split('T')[0];
    return order.checkOutDate <= today;
  };

  const getStatusTimeline = () => {
    const items = [];

    if (order.createdAt) {
      items.push({
        color: 'blue',
        children: (
          <>
            <p><strong>订单创建</strong></p>
            <p style={{ color: '#999' }}>{order.createdAt}</p>
          </>
        ),
      });
    }

    if (order.paidAt) {
      items.push({
        color: 'green',
        children: (
          <>
            <p><strong>支付成功</strong></p>
            <p style={{ color: '#999' }}>{order.paidAt}</p>
          </>
        ),
      });
    }

    if (order.confirmedAt) {
      items.push({
        color: 'green',
        children: (
          <>
            <p><strong>商家确认</strong></p>
            <p style={{ color: '#999' }}>{order.confirmedAt}</p>
          </>
        ),
      });
    }

    if (order.checkedInAt) {
      items.push({
        color: 'orange',
        children: (
          <>
            <p><strong>办理入住</strong></p>
            <p style={{ color: '#999' }}>{order.checkedInAt}</p>
          </>
        ),
      });
    }

    if (order.completedAt) {
      items.push({
        color: 'green',
        children: (
          <>
            <p><strong>订单完成</strong></p>
            <p style={{ color: '#999' }}>{order.completedAt}</p>
          </>
        ),
      });
    }

    if (order.cancelledAt) {
      items.push({
        color: 'red',
        children: (
          <>
            <p><strong>订单取消</strong></p>
            <p style={{ color: '#999' }}>{order.cancelledAt}</p>
            {order.cancelReason && <p style={{ color: '#999' }}>原因：{order.cancelReason}</p>}
          </>
        ),
      });
    }

    if (order.refundedAt) {
      items.push({
        color: 'purple',
        children: (
          <>
            <p><strong>退款完成</strong></p>
            <p style={{ color: '#999' }}>{order.refundedAt}</p>
          </>
        ),
      });
    }

    return items;
  };

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

  if (!order) {
    return <div>订单不存在</div>;
  }

  // 兼容处理：如果旧订单的服务费和商家收入为0，则前端计算
  // 服务费基于用户实付金额计算
  const serviceFee = order.serviceFee || (Number(order.payAmount) * 0.05).toFixed(2);
  const merchantIncome = order.merchantIncome ||
    (Number(order.payAmount) - Number(serviceFee)).toFixed(2);

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

      <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 || order.status}
            </Tag>
          </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.roomCount || 1} 套</Descriptions.Item>
          <Descriptions.Item label="房费">¥{order.roomAmount}</Descriptions.Item>
          <Descriptions.Item label="优惠券折扣">
            {order.couponDiscount ? `-¥${order.couponDiscount}` : '-'}
          </Descriptions.Item>
          <Descriptions.Item label="用户实付">
            <span style={{ color: '#ff4d4f', fontWeight: 'bold', fontSize: '16px' }}>
              ¥{order.payAmount}
            </span>
          </Descriptions.Item>
          <Descriptions.Item label="平台服务费">
            <span style={{ color: '#ff9800', fontSize: '14px' }}>
              ¥{serviceFee}
            </span>
            <span style={{ color: '#999', fontSize: '12px', marginLeft: 8 }}>
              (实付金额的5%)
            </span>
          </Descriptions.Item>
          <Descriptions.Item label="商家收入">
            <span style={{ color: '#52c41a', fontWeight: 'bold', fontSize: '16px' }}>
              ¥{merchantIncome}
            </span>
            <span style={{ color: '#999', fontSize: '12px', marginLeft: 8 }}>
              (实付金额 - 服务费)
            </span>
          </Descriptions.Item>
          <Descriptions.Item label="支付方式">{order.payMethod === 'wechat' ? '微信支付' : order.payMethod}</Descriptions.Item>
          <Descriptions.Item label="创建时间" span={2}>{order.createdAt}</Descriptions.Item>
        </Descriptions>

        <Divider />

        <Space>
          {order.status === 'pending_confirm' && (
            <>
              <Button type="primary" onClick={handleConfirm}>确认订单</Button>
              <Button danger onClick={() => setRejectModal({ visible: true, reason: '' })}>拒绝订单</Button>
            </>
          )}
          {order.status === 'pending_checkin' && (
            <Button type="primary" onClick={handleCheckin}>办理入住</Button>
          )}
          {canCheckout() && (
            <Button type="primary" onClick={handleCheckout}>确认离店</Button>
          )}
        </Space>
      </Card>

      <Card title="房源信息" style={{ marginBottom: 16 }}>
        <Descriptions column={2} bordered>
          <Descriptions.Item label="房源名称">{order.room?.name}</Descriptions.Item>
          <Descriptions.Item label="房型">{order.room?.roomType}</Descriptions.Item>
          <Descriptions.Item label="房间号">{order.roomNumber || '-'}</Descriptions.Item>
          <Descriptions.Item label="可住人数">{order.room?.capacity} 人</Descriptions.Item>
          <Descriptions.Item label="房源地址" span={2}>{order.room?.address}</Descriptions.Item>
        </Descriptions>
      </Card>

      <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="入住人数">{order.guestCount} 人</Descriptions.Item>
          <Descriptions.Item label="备注" span={2}>{order.remark || '-'}</Descriptions.Item>
        </Descriptions>
      </Card>

      {order.user && (
        <Card title="用户信息" style={{ marginBottom: 16 }}>
          <Descriptions column={2} bordered>
            <Descriptions.Item label="用户昵称">{order.user.nickname}</Descriptions.Item>
            <Descriptions.Item label="手机号">{order.user.phone}</Descriptions.Item>
          </Descriptions>
        </Card>
      )}

      <Card title="状态流转记录">
        <Timeline items={getStatusTimeline()} />
      </Card>

      <Modal
        title="拒绝订单"
        open={rejectModal.visible}
        onOk={handleReject}
        onCancel={() => setRejectModal({ visible: false, reason: '' })}
      >
        <Input.TextArea
          rows={3}
          placeholder="请输入拒绝原因"
          value={rejectModal.reason}
          onChange={(e) => setRejectModal({ ...rejectModal, reason: e.target.value })}
        />
      </Modal>
    </div>
  );
};

export default OrderDetail;
