import React, { useState, useEffect } from 'react'
import { View, Text, ScrollView, Button } from '@tarojs/components'
import { useRouter } from '@tarojs/taro'
import { useQuery } from '@tanstack/react-query'
import { routeClient } from '../../api'

interface Route {
  id: number
  name: string
  description: string | null
  startLocationId: number
  endLocationId: number
  startLocation: {
    id: number
    name: string
    provinceId: number
    cityId: number
    districtId: number
    address: string
  }
  endLocation: {
    id: number
    name: string
    provinceId: number
    cityId: number
    districtId: number
    address: string
  }
  pickupPoint: string
  dropoffPoint: string
  departureTime: string
  vehicleType: string
  price: number
  seatCount: number
  availableSeats: number
  activityId: number
  activity: {
    id: number
    name: string
    description: string | null
    venueLocationId: number
    venueLocation: {
      id: number
      name: string
      provinceId: number
      cityId: number
      districtId: number
      address: string
    }
    startDate: string
    endDate: string
  }
  routeType: 'departure' | 'return'
  isDisabled: number
  isDeleted: number
  createdAt: string
  updatedAt: string
}

const ScheduleListPage: React.FC = () => {
  const router = useRouter()
  const [selectedDate, setSelectedDate] = useState<string>('')
  const [dateOptions, setDateOptions] = useState<string[]>([])

  // 从路由参数获取查询条件
  const searchParams = {
    startAreaIds: router.params.startAreaIds ? JSON.parse(router.params.startAreaIds) as number[] : [],
    endAreaIds: router.params.endAreaIds ? JSON.parse(router.params.endAreaIds) as number[] : [],
    date: router.params.date || new Date().toISOString().split('T')[0],
    vehicleType: router.params.vehicleType || 'bus',
    activityId: Number(router.params.activityId),
    routeType: router.params.routeType as 'departure' | 'return'
  }

  // 生成日期选项
  useEffect(() => {
    const today = new Date()
    const dates: string[] = []
    for (let i = 0; i < 7; i++) {
      const date = new Date(today)
      date.setDate(today.getDate() + i)
      dates.push(date.toISOString().split('T')[0])
    }
    setDateOptions(dates)
    setSelectedDate(searchParams.date)
  }, [searchParams.date])

  // 查询路线
  const { data: routeData, isLoading } = useQuery({
    queryKey: ['routes', 'search', { ...searchParams, date: selectedDate }],
    queryFn: async () => {
      const res = await routeClient.search.$get({
        query: {
          startAreaIds: JSON.stringify(searchParams.startAreaIds),
          endAreaIds: JSON.stringify(searchParams.endAreaIds),
          date: selectedDate,
          routeType: searchParams.routeType,
          sortBy: 'departureTime',
          sortOrder: 'ASC'
        }
      })
      if (res.status !== 200) throw new Error('查询路线失败')
      const data = await res.json()
      return data.data || { routes: [], activities: [] }
    },
    enabled: !!selectedDate && !!searchParams.routeType && searchParams.startAreaIds?.length > 0 && searchParams.endAreaIds?.length > 0
  })

  const routes = routeData?.routes || []

  // 过滤包含指定活动的路线
  const filteredRoutes = routes.filter((route: Route) =>
    route.activityId === searchParams.activityId
  )

  // 处理日期选择
  const handleDateChange = (date: string) => {
    setSelectedDate(date)
  }

  // 预订路线
  const handleBookRoute = (route: Route) => {
    // 这里可以导航到订单确认页面
    console.log('预订路线:', route)
    // 临时提示
    // Taro.showToast({
    //   title: '预订功能开发中',
    //   icon: 'none'
    // })
  }

  // 获取车辆类型显示名称
  const getVehicleTypeName = (type: string) => {
    switch (type) {
      case 'bus': return '大巴拼车'
      case 'business': return '商务拼车'
      case 'charter': return '包车'
      default: return type
    }
  }

  // 获取路线类型标签
  const getRouteTypeLabel = () => {
    return searchParams.routeType === 'departure' ? '去程' : '返程'
  }

  // 格式化时间
  const formatTime = (timeString: string) => {
    const date = new Date(timeString)
    return date.toLocaleTimeString('zh-CN', {
      hour: '2-digit',
      minute: '2-digit'
    })
  }

  // 格式化价格
  const formatPrice = (price: number, vehicleType: string) => {
    if (vehicleType === 'charter') {
      return `¥${price}/车`
    }
    return `¥${price}/人`
  }

  // 获取活动名称
  const getActivityName = () => {
    if (!routeData?.activities || routeData.activities.length === 0) return ''
    const activity = routeData.activities.find(a => a.id === searchParams.activityId)
    return activity?.name || ''
  }

  const activityName = getActivityName()

  if (isLoading) {
    return (
      <View className="min-h-screen bg-gray-50 flex items-center justify-center">
        <Text className="text-gray-500">加载中...</Text>
      </View>
    )
  }

  return (
    <View className="min-h-screen bg-gray-50">
      {/* 头部信息 */}
      <View className="bg-white p-4 border-b border-gray-200">
        {activityName && (
          <Text className="text-lg font-bold text-gray-800 block">
            {activityName}
          </Text>
        )}
        <Text className="text-base text-gray-600 mt-1 block">
          {routes[0]?.startLocation.name} → {routes[0]?.endLocation.name}
        </Text>
        <View className="mt-2">
          <Text className="text-sm bg-blue-100 text-blue-800 px-2 py-1 rounded-full">
            {getRouteTypeLabel()}
          </Text>
        </View>
      </View>

      {/* 日期选择 */}
      <View className="bg-white p-4 border-b border-gray-200">
        <Text className="text-base font-medium text-gray-800 mb-3 block">
          选择出发日期
        </Text>
        <ScrollView scrollX className="whitespace-nowrap">
          <View className="flex space-x-2">
            {dateOptions.map(date => (
              <View
                key={date}
                className={`inline-flex flex-col items-center px-4 py-2 rounded-lg border-2 min-w-20 ${
                  selectedDate === date
                    ? 'border-blue-500 bg-blue-50'
                    : 'border-gray-200 bg-white'
                }`}
                onClick={() => handleDateChange(date)}
              >
                <Text
                  className={`text-sm ${
                    selectedDate === date ? 'text-blue-600 font-bold' : 'text-gray-600'
                  }`}
                >
                  {date}
                </Text>
                {date === new Date().toISOString().split('T')[0] && (
                  <Text className="text-xs text-gray-400 mt-1">今日</Text>
                )}
              </View>
            ))}
          </View>
        </ScrollView>
      </View>

      {/* 班次列表 */}
      <ScrollView className="flex-1">
        <View className="p-4">
          <View className="mb-4">
            <Text className="text-base font-medium text-gray-800">
              可选班次
            </Text>
            <Text className="text-sm text-gray-500 ml-2">
              ({filteredRoutes.length}个班次)
            </Text>
          </View>

          {filteredRoutes.length > 0 ? (
            <View className="space-y-4">
              {filteredRoutes.map((route: Route) => (
                <View
                  key={route.id}
                  className="bg-white rounded-lg border border-gray-200 p-4 shadow-sm"
                >
                  {/* 时间信息和价格 */}
                  <View className="flex justify-between items-start mb-3">
                    <View>
                      <Text className="text-xl font-bold text-gray-800">
                        {formatTime(route.departureTime)}
                      </Text>
                      <Text className="text-sm text-gray-500 mt-1 block">
                        预计时长：约2小时
                      </Text>
                    </View>
                    <View className="text-right">
                      <Text className="text-2xl font-bold text-orange-500">
                        {formatPrice(route.price, route.vehicleType)}
                      </Text>
                    </View>
                  </View>

                  {/* 车辆信息 */}
                  <View className="flex justify-between items-center mb-3">
                    <Text className="text-sm text-gray-600">
                      {getVehicleTypeName(route.vehicleType)}
                    </Text>
                    <View className="bg-blue-100 text-blue-800 text-xs px-2 py-1 rounded-full">
                      {route.vehicleType === 'charter' ? '包车' : '拼车'}
                    </View>
                  </View>

                  {/* 地点信息 */}
                  <View className="space-y-2 mb-3">
                    <View className="flex items-start">
                      <Text className="text-sm text-gray-500 w-12 flex-shrink-0">
                        上车：
                      </Text>
                      <Text className="text-sm text-gray-800 flex-1">
                        {route.pickupPoint}
                      </Text>
                    </View>
                    <View className="flex items-start">
                      <Text className="text-sm text-gray-500 w-12 flex-shrink-0">
                        下车：
                      </Text>
                      <Text className="text-sm text-gray-800 flex-1">
                        {route.dropoffPoint}
                      </Text>
                    </View>
                  </View>

                  {/* 座位信息 */}
                  <View className="flex justify-between items-center mb-3">
                    <Text className="text-sm text-gray-500">
                      {route.vehicleType === 'charter'
                        ? `可载${route.seatCount}人`
                        : `剩余${route.availableSeats}/${route.seatCount}座`}
                    </Text>
                    <View className="flex space-x-1">
                      <Text className="text-xs bg-green-100 text-green-800 px-2 py-1 rounded-full">
                        空调
                      </Text>
                      <Text className="text-xs bg-green-100 text-green-800 px-2 py-1 rounded-full">
                        免费WiFi
                      </Text>
                    </View>
                  </View>

                  {/* 预订按钮 */}
                  <Button
                    className={`w-full py-3 rounded-lg text-base font-medium ${
                      route.availableSeats === 0
                        ? 'bg-gray-300 text-gray-500'
                        : route.vehicleType === 'charter'
                        ? 'bg-green-500 text-white'
                        : 'bg-blue-500 text-white'
                    }`}
                    onClick={() => handleBookRoute(route)}
                    disabled={route.availableSeats === 0}
                  >
                    {route.availableSeats === 0
                      ? '已售罄'
                      : route.vehicleType === 'charter'
                      ? '立即包车'
                      : '立即购票'}
                  </Button>
                </View>
              ))}
            </View>
          ) : (
            <View className="bg-white rounded-lg border border-gray-200 p-8 text-center">
              <Text className="text-4xl mb-4">🚌</Text>
              <Text className="text-lg text-gray-600 block mb-2">暂无班次</Text>
              <Text className="text-sm text-gray-500">请选择其他日期查看</Text>
            </View>
          )}
        </View>
      </ScrollView>
    </View>
  )
}

export default ScheduleListPage