import { useState, useEffect } from 'react';
import { View, Text, ScrollView, Button } from '@tarojs/components';
import Taro from '@tarojs/taro';
import { useQuery } from '@tanstack/react-query';
import { orderClient } from '@/api';
import { OrderStatus } from '@/types/order.types';
import { TabBarLayout } from '@/layouts/tab-bar-layout';
import { Navbar } from '@/components/ui/navbar';

// 订单状态选项卡
const statusTabs = [
  { 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 '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';
    }
  };

  return (
    <View
      className="bg-card rounded-card shadow-medium p-card border border-border mb-4"
      onClick={() => onViewDetail(order.id)}
    >
      {/* 订单头部 */}
      <View className="flex justify-between items-start mb-3">
        <View className="flex-1">
          <Text className="text-sm text-muted-foreground">订单号：{order.id}</Text>
          <Text className="block text-base font-medium mt-1">
            {order.routeSnapshot?.name || '未知活动'}
          </Text>
        </View>
        <View className={`px-2 py-1 rounded-full text-xs font-medium ${getStatusColor(order.status)}`}>
          {order.status}
        </View>
      </View>

      {/* 行程信息 */}
      <View className="mb-3">
        <View className="flex items-center mb-2">
          <View className="flex-1">
            <Text className="text-sm text-muted-foreground">出发</Text>
            <Text className="block text-sm">{order.routeSnapshot?.pickupPoint}</Text>
          </View>
          <Text className="mx-2 text-muted-foreground">→</Text>
          <View className="flex-1">
            <Text className="text-sm text-muted-foreground">到达</Text>
            <Text className="block text-sm">{order.routeSnapshot?.dropoffPoint}</Text>
          </View>
        </View>

        <View className="space-y-1 text-sm">
          <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>
      </View>

      {/* 价格信息 */}
      <View className="flex justify-between items-center border-t border-border pt-3">
        <Text className="text-sm text-muted-foreground">
          下单时间：{new Date(order.createdAt).toLocaleString('zh-CN')}
        </Text>
        <View className="flex items-center">
          <Text className="text-sm text-muted-foreground mr-2">订单金额</Text>
          <Text className="text-lg font-semibold text-primary">¥{order.totalAmount}</Text>
        </View>
      </View>

      {/* 操作按钮 */}
      <View className="flex justify-end mt-3">
        <Button
          className="bg-primary text-primary-foreground px-4 py-2 rounded-md text-sm"
          onClick={(e) => {
            e.stopPropagation();
            onViewDetail(order.id);
          }}
        >
          查看详情
        </Button>
      </View>
    </View>
  );
};

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

  return (
    <View className="flex flex-col items-center justify-center py-16">
      <Text className="text-4xl mb-4">📋</Text>
      <Text className="text-lg text-muted-foreground mb-2">{getEmptyMessage()}</Text>
      <Text className="text-sm text-muted-foreground">您还没有相关状态的订单</Text>
    </View>
  );
};

const OrdersPage = () => {
  const [currentTab, setCurrentTab] = useState<OrderStatus>(OrderStatus.WAITING_DEPARTURE);

  // 获取订单列表
  const { data: ordersData, isLoading, error, refetch } = useQuery({
    queryKey: ['orders', currentTab],
    queryFn: async () => {
      const response = await orderClient.$get({
        query: {
          status: currentTab,
          page: 1,
          pageSize: 20
        }
      });

      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: OrderStatus) => {
    setCurrentTab(status);
  };

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

  useEffect(() => {
    // 启用下拉刷新
    Taro.startPullDownRefresh({
      success: () => {
        console.log('下拉刷新开始');
      }
    });
  }, []);

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

  return (
    <TabBarLayout activeKey="orders" className='bg-background'>
      <Navbar
        title="我的订单"
        leftIcon=""
        rightIcon=""
      />
      {/* 状态选项卡 */}
      <View className="bg-white border-b border-border">
        <ScrollView
          className="px-4"
          scrollX
          showScrollbar={false}
        >
          <View className="flex flex-row py-3">
            {statusTabs.map((tab) => (
              <View
                key={tab.key}
                className={`px-4 py-2 rounded-full mr-3 cursor-pointer transition-colors ${currentTab === tab.key
                    ? 'bg-primary text-primary-foreground'
                    : 'bg-muted text-muted-foreground'
                  }`}
                onClick={() => handleTabChange(tab.key)}
              >
                <Text className="text-sm font-medium">{tab.label}</Text>
              </View>
            ))}
          </View>
        </ScrollView>
      </View>

      {/* 订单列表 */}
      <ScrollView
        className="px-4 py-4"
        scrollY
        refresherEnabled
        onRefresherRefresh={onPullDownRefresh}
      >
        {isLoading ? (
          <View className="flex flex-col items-center justify-center py-16">
            <Text className="text-muted-foreground">加载中...</Text>
          </View>
        ) : orders.length === 0 ? (
          <EmptyOrders currentTab={currentTab} />
        ) : (
          orders.map((order) => (
            <OrderCard
              key={order.id}
              order={order}
              onViewDetail={handleViewDetail}
            />
          ))
        )}
      </ScrollView>
    </TabBarLayout>
  );
};

export default OrdersPage;