import { useState } from 'react';
import { View, Text, ScrollView } from '@tarojs/components';
import { Button } from '@/components/ui/button';
import Taro from '@tarojs/taro';
import { useQuery } 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 { TabBarLayout } from '@/layouts/tab-bar-layout';
import { Navbar } from '@/components/ui/navbar';

// 订单状态选项卡
const statusTabs = [
  { key: 'all', label: '全部' },
  { key: OrderStatus.WAITING_DEPARTURE, label: '待出发' },
  { key: OrderStatus.IN_PROGRESS, label: '行程中' },
  { key: OrderStatus.COMPLETED, label: '已完成' },
  { key: OrderStatus.CANCELLED, label: '已取消' }
];

// 订单卡片组件
const OrderCard = ({ order, onViewDetail }) => {
  const getStatusColor = (status: OrderStatus) => {
    switch (status) {
      case OrderStatus.WAITING_DEPARTURE:
        return 'bg-warning/15 text-warning border-warning/30';
      case OrderStatus.IN_PROGRESS:
        return 'bg-info/15 text-info border-info/30';
      case OrderStatus.COMPLETED:
        return 'bg-success/15 text-success border-success/30';
      case OrderStatus.CANCELLED:
        return 'bg-error/15 text-error border-error/30';
      default:
        return 'bg-gray-100 text-muted-foreground border-gray-200';
    }
  };

  // 判断是否为包车订单
  const isCharterOrder = order.routeSnapshot?.vehicleType === 'business' || order.routeSnapshot?.travelMode === 'charter';

  return (
    <View
      className={`mb-6 rounded-[28rpx] shadow-medium backdrop-blur-[16rpx] border border-white/40 overflow-hidden transition-all active:translate-y-[2rpx] active:shadow-[0_8rpx_24rpx_rgba(74,144,194,0.12)] ${
        isCharterOrder
          ? 'bg-gradient-to-br from-charter-dark to-charter-bg border-2 border-charter shadow-charter'
          : 'bg-white/96'
      }`}
      onClick={() => onViewDetail(order.id)}
    >
      {/* 订单头部 */}
      <View className="flex justify-between items-start p-[36rpx] border-b border-gray-200/60">
        <View className="flex-1">
          <Text className={`text-[24rpx] ${isCharterOrder ? 'text-gray-300' : 'text-gray-500'}`}>
            订单号：{order.id}
          </Text>
          <Text className={`block text-[34rpx] font-semibold mt-2 leading-[1.4] tracking-[0.5rpx] ${
            isCharterOrder ? 'text-charter' : 'text-gray-900'
          }`}>
            {order.routeSnapshot?.name || '未知活动'}
          </Text>
        </View>
        <View className={`px-[20rpx] py-[8rpx] rounded-[20rpx] text-[24rpx] font-bold border ${getStatusColor(order.status)}`}>
          {order.status}
        </View>
      </View>

      {/* 行程信息 */}
      <View className="p-[28rpx_36rpx_32rpx]">
        {/* 路线信息 */}
        <View className="flex items-center mb-[28rpx] p-[20rpx] bg-primary/5 rounded-[16rpx] border border-primary/10">
          <View className="flex-1">
            <Text className={`text-[24rpx] ${isCharterOrder ? 'text-gray-300' : 'text-gray-500'}`}>出发</Text>
            <Text className={`block text-[30rpx] font-semibold leading-[1.3] ${
              isCharterOrder ? 'text-white' : 'text-gray-900'
            }`}>
              {order.routeSnapshot?.pickupPoint}
            </Text>
          </View>
          <Text className={`mx-[28rpx] text-[36rpx] font-semibold opacity-80 ${
            isCharterOrder ? 'text-charter' : 'text-primary'
          }`}>
            →
          </Text>
          <View className="flex-1">
            <Text className={`text-[24rpx] ${isCharterOrder ? 'text-gray-300' : 'text-gray-500'}`}>到达</Text>
            <Text className={`block text-[30rpx] font-semibold leading-[1.3] ${
              isCharterOrder ? 'text-white' : 'text-gray-900'
            }`}>
              {order.routeSnapshot?.dropoffPoint}
            </Text>
          </View>
        </View>

        {/* 行程详情 */}
        <View className={`p-[24rpx] rounded-[18rpx] border ${
          isCharterOrder
            ? 'bg-gray-800 border-gray-700'
            : 'bg-primary/6 border-primary/8'
        }`}>
          <View className="flex mb-[16rpx] items-center">
            <Text className={`text-[26rpx] w-[160rpx] flex-shrink-0 ${
              isCharterOrder ? 'text-gray-300' : 'text-gray-600'
            }`}>
              出发时间：
            </Text>
            <Text className={`text-[26rpx] flex-1 ${
              isCharterOrder ? 'text-white' : 'text-gray-900'
            }`}>
              {order.routeSnapshot?.departureTime
                ? format(new Date(order.routeSnapshot.departureTime), 'yyyy-MM-dd HH:mm:ss', { locale: zhCN })
                : '未知时间'
              }
            </Text>
          </View>
          <View className="flex mb-[16rpx] items-center">
            <Text className={`text-[26rpx] w-[160rpx] flex-shrink-0 ${
              isCharterOrder ? 'text-gray-300' : 'text-gray-600'
            }`}>
              车辆型号：
            </Text>
            <Text className={`text-[26rpx] flex-1 ${
              isCharterOrder ? 'text-white' : 'text-gray-900'
            }`}>
              {getVehicleTypeText(order.routeSnapshot?.vehicleType)}
            </Text>
          </View>
          <View className="flex mb-[16rpx] items-center">
            <Text className={`text-[26rpx] w-[160rpx] flex-shrink-0 ${
              isCharterOrder ? 'text-gray-300' : 'text-gray-600'
            }`}>
              出行方式：
            </Text>
            <Text className={`text-[26rpx] flex-1 ${
              isCharterOrder ? 'text-white' : 'text-gray-900'
            }`}>
              {getTravelModeText(order.routeSnapshot?.travelMode)}
            </Text>
          </View>
          <View className="flex items-center">
            <Text className={`text-[26rpx] w-[160rpx] flex-shrink-0 ${
              isCharterOrder ? 'text-gray-300' : 'text-gray-600'
            }`}>
              乘车人数：
            </Text>
            <Text className={`text-[26rpx] flex-1 ${
              isCharterOrder ? 'text-white' : 'text-gray-900'
            }`}>
              {order.passengerCount}人
            </Text>
          </View>
        </View>
      </View>

      {/* 价格和操作区域 */}
      <View className={`p-[28rpx_36rpx] border-t ${
        isCharterOrder
          ? 'bg-gray-800 border-gray-700'
          : 'bg-primary/4 border-primary/8'
      }`}>
        <View className="flex justify-between items-center mb-3">
          <Text className={`text-[26rpx] flex-1 min-w-0 font-medium leading-[1.4] ${
            isCharterOrder ? 'text-gray-300' : 'text-gray-500'
          }`}>
            下单时间：{format(new Date(order.createdAt), 'yyyy-MM-dd HH:mm:ss', { locale: zhCN })}
          </Text>
          <View className="flex items-center flex-shrink-0">
            <Text className={`text-[28rpx] mr-2 ${
              isCharterOrder ? 'text-gray-300' : 'text-gray-600'
            }`}>
              订单金额
            </Text>
            <Text className={`text-[36rpx] font-bold ${
              isCharterOrder ? 'text-charter' : 'text-primary'
            }`}>
              ¥{order.totalAmount}
            </Text>
          </View>
        </View>

        {/* 操作按钮 */}
        <View className="flex justify-end w-full">
          <Button
            className={`rounded-[50rpx] px-[28rpx] py-[16rpx] text-[26rpx] font-semibold shadow-primary transition-all active:translate-y-[1rpx] active:shadow-[0_4rpx_12rpx_rgba(74,144,194,0.25)] ${
              isCharterOrder
                ? 'bg-charter text-charter-dark'
                : 'bg-gradient-to-br from-primary to-primary-dark text-white'
            }`}
            onClick={(e) => {
              e.stopPropagation();
              onViewDetail(order.id);
            }}
          >
            查看详情
          </Button>
        </View>
      </View>
    </View>
  );
};

// 空状态组件
const EmptyOrders = ({ currentTab }) => {
  const getEmptyMessage = () => {
    switch (currentTab) {
      case 'all':
        return '暂无订单';
      case OrderStatus.WAITING_DEPARTURE:
        return '暂无待出发订单';
      case OrderStatus.IN_PROGRESS:
        return '暂无行程中订单';
      case OrderStatus.COMPLETED:
        return '暂无已完成订单';
      case OrderStatus.CANCELLED:
        return '暂无已取消订单';
      default:
        return '暂无订单';
    }
  };

  return (
    <View className="text-center p-[120rpx_32rpx] bg-white/10 rounded-[24rpx] backdrop-blur-[10rpx] border border-white/20 mx-auto my-[32rpx] w-full max-w-[680rpx] box-border">
      <Text className="text-[120rpx] mb-[32rpx] text-white/80">📋</Text>
      <Text className="text-[32rpx] text-white/90 mb-[16rpx] font-bold">{getEmptyMessage()}</Text>
      <Text className="text-[26rpx] text-white/70">您还没有相关状态的订单</Text>
    </View>
  );
};

const OrdersPage = () => {
  const [currentTab, setCurrentTab] = useState<string>('all');

  // 获取订单列表
  const { data: ordersData, isLoading, error, refetch } = useQuery({
    queryKey: ['orders', currentTab],
    queryFn: async () => {
      const queryParams: any = {
        page: 1,
        pageSize: 20
      };

      // 如果不是"全部"标签，则添加状态筛选
      if (currentTab !== 'all') {
        queryParams.status = currentTab;
      }

      const response = await orderClient.$get({
        query: queryParams
      });

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

      return response.json();
    }
  });

  const orders = ordersData?.data || [];

  // 查看订单详情
  const handleViewDetail = (orderId: number) => {
    Taro.navigateTo({
      url: `/pages/order-detail/index?id=${orderId}`
    });
  };

  // 切换选项卡
  const handleTabChange = (status: string) => {
    setCurrentTab(status);
  };

  // 下拉刷新
  const onPullDownRefresh = async () => {
    await refetch();
    Taro.stopPullDownRefresh();
  };

  if (error) {
    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={() => refetch()}
        >
          重新加载
        </Button>
      </View>
    );
  }

  return (
    <TabBarLayout activeKey="orders" className='bg-gradient-to-b from-primary to-primary-dark min-h-screen'>
      <Navbar
        title="我的订单"
        backgroundColor="bg-transparent"
        textColor="text-white"
        border={false}
        leftIcon=""
        rightIcon=""
      />

      {/* 状态选项卡 */}
      <View className="bg-white/95 p-[24rpx_20rpx] rounded-[24rpx] shadow-medium backdrop-blur-[12rpx] mx-auto mt-[24rpx] max-w-[700rpx] w-[calc(100%-32rpx)]">
        <ScrollView
          scrollX
          showScrollbar={false}
        >
          <View className="flex justify-between items-center w-full box-border p-0 gap-[12rpx]">
            {statusTabs.map((tab) => (
              <View
                key={tab.key}
                className={`flex items-center justify-center p-[16rpx_20rpx] rounded-[50rpx] text-[26rpx] font-medium transition-all whitespace-nowrap overflow-hidden text-ellipsis min-w-0 tracking-[0.5rpx] flex-1 text-center border-2 ${
                  currentTab === tab.key
                    ? 'bg-gradient-to-br from-primary to-primary-dark text-white font-semibold -translate-y-[2rpx] shadow-[0_6rpx_20rpx_rgba(74,144,194,0.35)] border-primary/30'
                    : 'bg-primary/8 text-gray-600 border-primary/15'
                }`}
                onClick={() => handleTabChange(tab.key)}
              >
                <Text>{tab.label}</Text>
              </View>
            ))}
          </View>
        </ScrollView>
      </View>

      {/* 订单列表 */}
      <ScrollView
        className="p-[40rpx_16rpx_32rpx] flex flex-col items-center w-full box-border"
        scrollY
        refresherEnabled
        onRefresherRefresh={onPullDownRefresh}
      >
        {isLoading ? (
          <View className="flex flex-col items-center justify-center py-16">
            <Text className="text-white/80">加载中...</Text>
          </View>
        ) : orders.length === 0 ? (
          <EmptyOrders currentTab={currentTab} />
        ) : (
          orders.map((order) => (
            <OrderCard
              key={order.id}
              order={order}
              onViewDetail={handleViewDetail}
            />
          ))
        )}
        {/* 底部占位，避免被tabbar遮挡 */}
        <View className="h-16"></View>
      </ScrollView>
    </TabBarLayout>
  );
};

export default OrdersPage;