import { useState, useEffect } from 'react';
import { View, Text, ScrollView, Button } from '@tarojs/components';
import Taro from '@tarojs/taro';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { orderClient } from '@/api';
import { OrderStatus } from '@/types/order.types';

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-warning';
      case OrderStatus.IN_PROGRESS:
        return 'text-info';
      case OrderStatus.COMPLETED:
        return 'text-success';
      case OrderStatus.CANCELLED:
        return 'text-error';
      default:
        return 'text-muted-foreground';
    }
  };

  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
          className="bg-primary text-primary-foreground px-4 py-2 rounded-md"
          onClick={() => Taro.navigateBack()}
        >
          返回
        </Button>
      </View>
    );
  }

  return (
    <View className="min-h-screen bg-background">
      <ScrollView className="px-4 py-4" scrollY>
        {/* 订单基本信息 */}
        <View className="bg-card rounded-card shadow-medium p-card border border-border mb-4">
          <Text className="text-lg font-semibold mb-4">订单信息</Text>

          <View className="space-y-3">
            <View className="flex justify-between">
              <Text className="text-muted-foreground">订单号：</Text>
              <Text>{order.id}</Text>
            </View>

            <View className="flex justify-between">
              <Text className="text-muted-foreground">行程路线：</Text>
              <Text className="text-right">
                {order.routeSnapshot?.pickupPoint} → {order.routeSnapshot?.dropoffPoint}
              </Text>
            </View>

            <View className="flex justify-between">
              <Text className="text-muted-foreground">出发时间：</Text>
              <Text>
                {order.routeSnapshot?.departureTime
                  ? new Date(order.routeSnapshot.departureTime).toLocaleString('zh-CN')
                  : '未知时间'
                }
              </Text>
            </View>

            <View className="flex justify-between">
              <Text className="text-muted-foreground">车辆型号：</Text>
              <Text>{order.routeSnapshot?.vehicleType || '未知车型'}</Text>
            </View>

            <View className="flex justify-between">
              <Text className="text-muted-foreground">乘车人数：</Text>
              <Text>{order.passengerCount}人</Text>
            </View>

            <View className="flex justify-between">
              <Text className="text-muted-foreground">订单状态：</Text>
              <Text className={`font-medium ${getStatusColor(order.status)}`}>
                {order.status}
              </Text>
            </View>

            <View className="flex justify-between">
              <Text className="text-muted-foreground">支付状态：</Text>
              <Text>{order.paymentStatus}</Text>
            </View>

            <View className="flex justify-between">
              <Text className="text-muted-foreground">订单金额：</Text>
              <Text className="text-lg font-semibold text-primary">¥{order.totalAmount}</Text>
            </View>

            <View className="flex justify-between">
              <Text className="text-muted-foreground">下单时间：</Text>
              <Text>{new Date(order.createdAt).toLocaleString('zh-CN')}</Text>
            </View>
          </View>
        </View>

        {/* 乘客信息 */}
        {order.passengerSnapshots && order.passengerSnapshots.length > 0 && (
          <View className="bg-card rounded-card shadow-medium p-card border border-border mb-4">
            <Text className="text-lg font-semibold mb-4">乘客信息</Text>

            <View className="space-y-3">
              {order.passengerSnapshots.map((passenger, index) => (
                <View key={index} className="border-b border-border pb-3 last:border-b-0 last:pb-0">
                  <View className="flex justify-between mb-1">
                    <Text className="font-medium">{passenger.name}</Text>
                    <Text className="text-sm text-muted-foreground">
                      {passenger.idType === 'ID_CARD' ? '身份证' : '护照'}
                    </Text>
                  </View>

                  <View className="space-y-1 text-sm">
                    <View className="flex justify-between">
                      <Text className="text-muted-foreground">证件号码：</Text>
                      <Text>{passenger.idNumber}</Text>
                    </View>

                    {passenger.phone && (
                      <View className="flex justify-between">
                        <Text className="text-muted-foreground">联系电话：</Text>
                        <Text>{passenger.phone}</Text>
                      </View>
                    )}
                  </View>
                </View>
              ))}
            </View>
          </View>
        )}

        {/* 路线快照信息 */}
        {order.routeSnapshot && (
          <View className="bg-card rounded-card shadow-medium p-card border border-border mb-4">
            <Text className="text-lg font-semibold mb-4">行程详情</Text>

            <View className="space-y-3">
              <View className="flex justify-between">
                <Text className="text-muted-foreground">活动名称：</Text>
                <Text>{order.routeSnapshot.name}</Text>
              </View>

              <View className="flex justify-between">
                <Text className="text-muted-foreground">出行方式：</Text>
                <Text>{order.routeSnapshot.travelMode === 'DRIVING' ? '驾车' : '其他'}</Text>
              </View>

              <View className="flex justify-between">
                <Text className="text-muted-foreground">单价：</Text>
                <Text>¥{order.routeSnapshot.price}</Text>
              </View>
            </View>
          </View>
        )}
      </ScrollView>

      {/* 底部操作按钮 */}
      {order.status === OrderStatus.WAITING_DEPARTURE && (
        <View className="fixed bottom-0 left-0 right-0 bg-white border-t border-border p-4">
          <Button
            className="bg-error text-error-foreground w-full py-3 rounded-md"
            onClick={handleCancelOrder}
            loading={cancelOrderMutation.isPending}
          >
            {cancelOrderMutation.isPending ? '取消中...' : '取消订单'}
          </Button>
        </View>
      )}
    </View>
  );
};

export default OrderDetailPage;