import React, { useState, useEffect } from 'react'
import { View, Text, ScrollView, Button } from '@tarojs/components'
import { useRouter, navigateTo, navigateBack } from '@tarojs/taro'
import { useQuery } from '@tanstack/react-query'
import { format } from 'date-fns'
import { zhCN } from 'date-fns/locale'
import { routeClient } from '../../api'
import { Navbar, NavbarPresets } from '@/components/ui/navbar'

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
  travelMode: 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',
    travelMode: router.params.travelMode || 'carpool',
    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,
          vehicleType: searchParams.vehicleType,
          travelMode: searchParams.travelMode,
          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) => {
    // 导航到订单确认页面
    navigateTo({
      url: `/pages/order/index?routeId=${route.id}&activityName=${encodeURIComponent(activityName)}&type=${route.travelMode}`
    })
  }

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

  // 获取出行方式显示名称
  const getTravelModeName = (mode: string) => {
    switch (mode) {
      case 'carpool': return '拼车'
      case 'charter': return '包车'
      default: return mode
    }
  }

  // 获取组合查询显示名称
  const getCombinationDisplayName = (vehicleType: string, travelMode: string) => {
    const vehicleName = getVehicleTypeName(vehicleType)
    const travelName = getTravelModeName(travelMode)
    return `${vehicleName}${travelName}`
  }

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

  // 格式化时间
  const formatTime = (timeString: string) => {
    const date = new Date(timeString)
    return format(date, 'HH:mm', { locale: zhCN })
  }

  // 格式化价格
  const formatPrice = (price: number, travelMode: string) => {
    if (travelMode === '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">
      {/* 导航栏 */}
      <Navbar
        title="选择班次"
        leftIcon="i-heroicons-arrow-left-20-solid"
        onClickLeft={() => navigateBack()}
        {...NavbarPresets.primary}
      />

      {/* 头部信息 */}
      <View className="bg-gradient-to-r from-primary to-primary-dark p-card">
        {activityName && (
          <Text className="text-lg font-bold text-white block">
            {activityName}
          </Text>
        )}
        <Text className="text-base text-white/90 mt-1 block">
          {routes[0]?.startLocation.name} → {routes[0]?.endLocation.name}
        </Text>
        <View className="mt-2">
          <Text className="text-sm bg-white/20 text-white px-2 py-1 rounded-small">
            {getRouteTypeLabel()}
          </Text>
        </View>
      </View>

      {/* 日期选择 */}
      <View className="bg-white p-card border-b border-gray-200 shadow-light">
        <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-medium border-2 min-w-20 ${
                  selectedDate === date
                    ? 'border-primary bg-primary/10'
                    : 'border-gray-200 bg-white'
                }`}
                onClick={() => handleDateChange(date)}
              >
                <Text
                  className={`text-sm ${
                    selectedDate === date ? 'text-primary 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-card border p-card shadow-medium ${
                    route.travelMode === 'charter'
                      ? 'border-charter bg-gradient-to-r from-charter-dark to-charter-bg'
                      : 'border-gray-200'
                  }`}
                >
                  {/* 时间信息和价格 */}
                  <View className="flex justify-between items-start mb-3">
                    <View>
                      <Text className={`text-xl font-bold ${
                        route.travelMode === 'charter' ? 'text-white' : 'text-gray-800'
                      }`}>
                        {formatTime(route.departureTime)}
                      </Text>
                      <Text className={`text-sm mt-1 block ${
                        route.travelMode === 'charter' ? 'text-white/80' : 'text-gray-500'
                      }`}>
                        预计时长：约2小时
                      </Text>
                    </View>
                    <View className="text-right">
                      <Text className={`text-2xl font-bold ${
                        route.travelMode === 'charter' ? 'text-charter' : 'text-orange-500'
                      }`}>
                        {formatPrice(route.price, route.travelMode)}
                      </Text>
                    </View>
                  </View>

                  {/* 车辆信息 */}
                  <View className="flex justify-between items-center mb-3">
                    <Text className={`text-sm ${
                      route.travelMode === 'charter' ? 'text-white/90' : 'text-gray-600'
                    }`}>
                      {getCombinationDisplayName(route.vehicleType, route.travelMode)}
                    </Text>
                    <View className={`text-xs px-2 py-1 rounded-small ${
                      route.travelMode === 'charter'
                        ? 'bg-charter/20 text-charter'
                        : 'bg-primary/10 text-primary'
                    }`}>
                      {getTravelModeName(route.travelMode)}
                    </View>
                  </View>

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

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

                  {/* 预订按钮 */}
                  <Button
                    className={`w-full py-button rounded-button text-base font-medium shadow-primary ${
                      route.availableSeats === 0
                        ? 'bg-gray-300 text-gray-500'
                        : route.travelMode === 'charter'
                        ? 'bg-gradient-to-r from-charter to-charter-light text-white'
                        : 'bg-gradient-to-r from-primary to-primary-dark text-white'
                    }`}
                    onClick={() => handleBookRoute(route)}
                    disabled={route.availableSeats === 0}
                  >
                    {route.availableSeats === 0
                      ? '已售罄'
                      : route.travelMode === 'charter'
                      ? '立即包车'
                      : '立即购票'}
                  </Button>
                </View>
              ))}
            </View>
          ) : (
            <View className="bg-white rounded-card border border-gray-200 p-8 text-center shadow-light">
              <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