import { useState, useEffect } from 'react';
import { View, Text, ScrollView } from '@tarojs/components';
import { Button } from '@/components/ui/button';
import Taro from '@tarojs/taro';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { format } from 'date-fns';
import { zhCN } from 'date-fns/locale';
import { orderClient } from '@/api';
import { OrderStatus } from '@/types/order.types';
import { getVehicleTypeText, getTravelModeText } from '@/types/route.types';
import { Navbar } from '@/components/ui/navbar';

const OrderDetailPage = () => {
  const [orderId, setOrderId] = useState<number | null>(null);
  const queryClient = useQueryClient();

  // 获取路由参数
  useEffect(() => {
    const params = Taro.getCurrentInstance().router?.params;
    if (params?.id) {
      setOrderId(Number(params.id));
    }
  }, []);

  // 获取订单详情
  const { data: order, isLoading, error } = useQuery({
    queryKey: ['order', orderId],
    queryFn: async () => {
      if (!orderId) throw new Error('订单ID不存在');

      const response = await orderClient[':id'].$get({
        param: { id: orderId }
      });

      if (!response.ok) {
        throw new Error('获取订单详情失败');
      }

      return response.json();
    },
    enabled: !!orderId
  });

  // 取消订单
  const cancelOrderMutation = useMutation({
    mutationFn: async () => {
      if (!orderId) throw new Error('订单ID不存在');

      const response = await orderClient[':id'].cancel.$post({
        param: { id: orderId }
      });

      if (!response.ok) {
        throw new Error('取消订单失败');
      }

      return response.json();
    },
    onSuccess: () => {
      // 刷新订单详情
      queryClient.invalidateQueries({ queryKey: ['order', orderId] });
      Taro.showToast({
        title: '订单已取消',
        icon: 'success'
      });

      // 1.5秒后返回订单列表
      setTimeout(() => {
        Taro.navigateBack();
      }, 1500);
    },
    onError: (error: Error) => {
      Taro.showToast({
        title: error.message,
        icon: 'none'
      });
    }
  });

  // 取消订单
  const handleCancelOrder = () => {
    if (!order) return;

    // 状态验证
    if (order.status !== OrderStatus.WAITING_DEPARTURE) {
      Taro.showToast({
        title: '订单状态不允许取消',
        icon: 'none'
      });
      return;
    }

    Taro.showModal({
      title: '确认取消订单',
      content: '取消后将无法恢复，确定要取消这个订单吗？',
      confirmText: '确认取消',
      cancelText: '再想想',
      confirmColor: '#ff4d4f',
      success: (res) => {
        if (res.confirm) {
          cancelOrderMutation.mutate();
        }
      }
    });
  };

  // 获取状态颜色
  const getStatusColor = (status: OrderStatus) => {
    switch (status) {
      case OrderStatus.WAITING_DEPARTURE:
        return 'text-[#FFA940]';
      case OrderStatus.IN_PROGRESS:
        return 'text-[#1890ff]';
      case OrderStatus.COMPLETED:
        return 'text-[#52C41A]';
      case OrderStatus.CANCELLED:
        return 'text-[#ff4d4f]';
      default:
        return 'text-gray-500';
    }
  };

  if (isLoading) {
    return (
      <View className="flex flex-col items-center justify-center py-16">
        <Text className="text-muted-foreground">加载中...</Text>
      </View>
    );
  }

  if (error || !order) {
    return (
      <View className="flex flex-col items-center justify-center py-16">
        <Text className="text-lg text-error mb-4">加载失败</Text>
        <Button
          variant="default"
          onClick={() => Taro.navigateBack()}
        >
          返回
        </Button>
      </View>
    );
  }

  return (
    <View className="min-h-screen bg-gradient-to-b from-[#5B9BD5] to-[#4A90C2] pb-[calc(100rpx+env(safe-area-inset-bottom))]">
      <Navbar
        title="订单详情"
        backgroundColor="bg-transparent"
        textColor="text-white"
        border={false}
        leftIcon="i-heroicons-arrow-left-20-solid"
        onClickLeft={() => Taro.navigateBack()}
        rightIcon=""
      />
      <ScrollView className="px-[32rpx] pt-4" scrollY>
        {/* 订单基本信息 */}
        <View className="bg-white/96 backdrop-blur-[16rpx] rounded-[28rpx] p-[36rpx] mb-[32rpx] shadow-[0_12rpx_40rpx_rgba(74,144,194,0.18)] border border-white/40">
          <Text className="text-[36rpx] font-semibold text-gray-900 mb-[24rpx] tracking-[0.5rpx]">订单信息</Text>
          <View className="space-y-[20rpx]">
            <View className="flex items-center">
              <Text className="text-[28rpx] text-gray-600 w-[160rpx] flex-shrink-0">订单号：</Text>
              <Text className="text-[28rpx] text-gray-900 flex-1 font-medium">{order.id}</Text>
            </View>

            <View className="flex items-center">
              <Text className="text-[28rpx] text-gray-600 w-[160rpx] flex-shrink-0">行程路线：</Text>
              <Text className="text-[28rpx] text-gray-900 flex-1 font-medium text-right">
                {order.routeSnapshot?.pickupPoint} → {order.routeSnapshot?.dropoffPoint}
              </Text>
            </View>

            <View className="flex items-center">
              <Text className="text-[28rpx] text-gray-600 w-[160rpx] flex-shrink-0">出发时间：</Text>
              <Text className="text-[28rpx] text-gray-900 flex-1 font-medium">
                {order.routeSnapshot?.departureTime
                  ? format(new Date(order.routeSnapshot.departureTime), 'yyyy-MM-dd HH:mm:ss', { locale: zhCN })
                  : '未知时间'
                }
              </Text>
            </View>

            <View className="flex items-center">
              <Text className="text-[28rpx] text-gray-600 w-[160rpx] flex-shrink-0">车辆型号：</Text>
              <Text className="text-[28rpx] text-gray-900 flex-1 font-medium">{getVehicleTypeText(order.routeSnapshot?.vehicleType)}</Text>
            </View>

            <View className="flex items-center">
              <Text className="text-[28rpx] text-gray-600 w-[160rpx] flex-shrink-0">乘车人数：</Text>
              <Text className="text-[28rpx] text-gray-900 flex-1 font-medium">{order.passengerCount}人</Text>
            </View>

            <View className="flex items-center">
              <Text className="text-[28rpx] text-gray-600 w-[160rpx] flex-shrink-0">订单状态：</Text>
              <Text className={`text-[28rpx] flex-1 font-medium ${getStatusColor(order.status)}`}>
                {order.status}
              </Text>
            </View>

            <View className="flex items-center">
              <Text className="text-[28rpx] text-gray-600 w-[160rpx] flex-shrink-0">支付状态：</Text>
              <Text className="text-[28rpx] text-gray-900 flex-1 font-medium">{order.paymentStatus}</Text>
            </View>

            <View className="flex items-center">
              <Text className="text-[28rpx] text-gray-600 w-[160rpx] flex-shrink-0">订单金额：</Text>
              <Text className="text-[30rpx] text-primary flex-1 font-semibold">¥{order.totalAmount}</Text>
            </View>

            <View className="flex items-center">
              <Text className="text-[28rpx] text-gray-600 w-[160rpx] flex-shrink-0">下单时间：</Text>
              <Text className="text-[28rpx] text-gray-900 flex-1 font-medium">{format(new Date(order.createdAt), 'yyyy-MM-dd HH:mm:ss', { locale: zhCN })}</Text>
            </View>
          </View>
        </View>

        {/* 乘客信息 */}
        {order.passengerSnapshots && order.passengerSnapshots.length > 0 && (
          <View className="bg-white/96 backdrop-blur-[16rpx] rounded-[28rpx] p-[36rpx] mb-[32rpx] shadow-[0_12rpx_40rpx_rgba(74,144,194,0.18)] border border-white/40">
            <Text className="text-[36rpx] font-semibold text-gray-900 mb-[24rpx] tracking-[0.5rpx]">乘客信息</Text>
            <View className="space-y-[24rpx]">
              {order.passengerSnapshots.map((passenger, index) => (
                <View key={index} className="border-b border-gray-200/60 pb-[24rpx] last:border-b-0 last:pb-0">
                  <View className="flex justify-between mb-[12rpx]">
                    <Text className="text-[28rpx] font-medium text-gray-900">{passenger.name}</Text>
                    <Text className="text-[24rpx] text-gray-500">
                      {passenger.idType === 'ID_CARD' ? '身份证' : '护照'}
                    </Text>
                  </View>

                  <View className="space-y-[8rpx] text-[24rpx]">
                    <View className="flex items-center">
                      <Text className="text-gray-600 w-[120rpx] flex-shrink-0">证件号码：</Text>
                      <Text className="text-gray-900 flex-1 font-medium">{passenger.idNumber}</Text>
                    </View>

                    {passenger.phone && (
                      <View className="flex items-center">
                        <Text className="text-gray-600 w-[120rpx] flex-shrink-0">联系电话：</Text>
                        <Text className="text-gray-900 flex-1 font-medium">{passenger.phone}</Text>
                      </View>
                    )}
                  </View>
                </View>
              ))}
            </View>
          </View>
        )}

        {/* 路线快照信息 */}
        {order.routeSnapshot && (
          <View className="bg-white/96 backdrop-blur-[16rpx] rounded-[28rpx] p-[36rpx] mb-[32rpx] shadow-[0_12rpx_40rpx_rgba(74,144,194,0.18)] border border-white/40">
            <Text className="text-[36rpx] font-semibold text-gray-900 mb-[24rpx] tracking-[0.5rpx]">行程详情</Text>
            <View className="space-y-[20rpx]">
              <View className="flex items-center">
                <Text className="text-[28rpx] text-gray-600 w-[160rpx] flex-shrink-0">活动名称：</Text>
                <Text className="text-[28rpx] text-gray-900 flex-1 font-medium">{order.routeSnapshot.name}</Text>
              </View>

              <View className="flex items-center">
                <Text className="text-[28rpx] text-gray-600 w-[160rpx] flex-shrink-0">出行方式：</Text>
                <Text className="text-[28rpx] text-gray-900 flex-1 font-medium">{getTravelModeText(order.routeSnapshot.travelMode)}</Text>
              </View>

              <View className="flex items-center">
                <Text className="text-[28rpx] text-gray-600 w-[160rpx] flex-shrink-0">单价：</Text>
                <Text className="text-[28rpx] text-gray-900 flex-1 font-medium">¥{order.routeSnapshot.price}</Text>
              </View>
            </View>
          </View>
        )}
        {/* 底部占位，避免被操作按钮遮挡 */}
        <View className="h-20"></View>
      </ScrollView>

      {/* 底部操作按钮 */}
      {order.status === OrderStatus.WAITING_DEPARTURE && (
        <View className="fixed bottom-0 left-0 right-0 bg-white/95 backdrop-blur-[12rpx] p-[24rpx_32rpx] pb-[calc(24rpx+env(safe-area-inset-bottom))] shadow-[0_-4rpx_20rpx_rgba(0,0,0,0.1)] border-t border-gray-200/60">
          <Button
            className="w-full bg-gradient-to-r from-[#ff4d4f] to-[#ff7875] text-white border-none rounded-[50rpx] p-[24rpx] text-[32rpx] font-semibold shadow-[0_8rpx_24rpx_rgba(255,77,79,0.3)] transition-all duration-300 ease-[cubic-bezier(0.4,0,0.2,1)] active:translate-y-[2rpx] active:shadow-[0_4rpx_12rpx_rgba(255,77,79,0.2)]"
            onClick={handleCancelOrder}
            loading={cancelOrderMutation.isPending}
          >
            {cancelOrderMutation.isPending ? '取消中...' : '取消订单'}
          </Button>
        </View>
      )}
    </View>
  );
};

export default OrderDetailPage;