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

interface Activity {
  id: number
  name: string
  description?: string
  type: 'departure' | 'return'
  startDate: string
  endDate: string
  imageUrl?: string
  venueLocationId: number
  venueLocation: {
    id: number
    name: string
    provinceId: number
    cityId: number
    districtId: number
    address: string
    latitude: string
    longitude: string
    province: {
      id: number
      name: string
      level: number
      code: string
      isDisabled: number
      isDeleted: number
      createdBy?: any
      updatedBy?: any
      createdAt: string
      updatedAt: string
    }
    city: {
      id: number
      name: string
      level: number
      code: string
      isDisabled: number
      isDeleted: number
      createdBy?: any
      updatedBy?: any
      createdAt: string
      updatedAt: string
    }
    district: {
      id: number
      name: string
      level: number
      code: string
      isDisabled: number
      isDeleted: number
      createdBy?: any
      updatedBy?: any
      createdAt: string
      updatedAt: string
    }
    isDisabled: number
    isDeleted: number
    createdBy?: any
    updatedBy?: any
    createdAt: string
    updatedAt: string
  }
  isDisabled: number
  isDeleted: number
  createdBy?: any
  updatedBy?: any
  createdAt: string
  updatedAt: string
}



const ActivitySelectPage: React.FC = () => {
  const router = useRouter()

  // 从路由参数获取查询条件
  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'
  }

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

  const activities = routeData?.activities || []

  // 分离去程和返程活动
  const departureActivities = (activities as Activity[])
    .filter((activity: Activity) => activity.type === 'departure')
    .filter((activity, index, self) =>
      index === self.findIndex(a => a.id === activity.id)
    )

  const returnActivities = (activities as Activity[])
    .filter((activity: Activity) => activity.type === 'return')
    .filter((activity, index, self) =>
      index === self.findIndex(a => a.id === activity.id)
    )

  // 选择活动
  const handleSelectActivity = (activity: Activity, routeType: 'departure' | 'return') => {
    // 导航到班次列表页面
    navigateTo({
      url: `/pages/schedule-list/ScheduleListPage?` +
        `startAreaIds=${JSON.stringify(searchParams.startAreaIds)}&` +
        `endAreaIds=${JSON.stringify(searchParams.endAreaIds)}&` +
        `date=${searchParams.date}&` +
        `vehicleType=${searchParams.vehicleType}&` +
        `activityId=${activity.id}&` +
        `routeType=${routeType}`
    })
  }

  // 获取活动显示信息
  const getActivityDisplayInfo = (activity: Activity) => {
    const venue = activity.venueLocation
    const locationParts: string[] = []
    if (venue.district?.name) locationParts.push(venue.district.name)
    if (venue.city?.name) locationParts.push(venue.city.name)
    if (venue.province?.name) locationParts.push(venue.province.name)

    return {
      location: locationParts.join(' · '),
      address: venue.address,
      date: new Date(activity.startDate).toLocaleDateString('zh-CN')
    }
  }

  // 获取路线信息显示
  const getRouteInfo = () => {
    // 这里可以根据省市区ID获取地区名称，暂时使用默认值
    return {
      fromCity: '出发地',
      toCity: '目的地'
    }
  }

  const routeInfo = getRouteInfo()

  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">
        <Text className="text-lg font-bold text-gray-800 block">
          {routeInfo.fromCity} → {routeInfo.toCity}
        </Text>
        <Text className="text-sm text-gray-500 mt-1">
          {searchParams.date}
        </Text>
      </View>


      <ScrollView className="flex-1">
        <View className="p-4">
          <Text className="text-lg font-bold text-gray-800 mb-2 block">
            选择观看活动
          </Text>
          <Text className="text-sm text-gray-500 mb-4 block">
            系统已为您自动匹配出发地和目的地的热门活动
          </Text>

          {/* 去程活动区域 */}
          <View className="mb-6">
            <View className="bg-gradient-to-r from-blue-500 to-blue-600 rounded-t-lg p-4">
              <View className="flex items-center mb-1">
                <Text className="text-white text-lg mr-2">✈️</Text>
                <Text className="text-white text-lg font-bold">去程活动</Text>
              </View>
              <Text className="text-white/90 text-sm">
                前往{routeInfo.toCity}观看活动
              </Text>
            </View>

            {departureActivities.length > 0 ? (
              <View className="bg-white rounded-b-lg border border-gray-200">
                {departureActivities.map(activity => {
                  const info = getActivityDisplayInfo(activity)
                  return (
                    <View
                      key={activity.id}
                      className="p-4 border-b border-gray-100 last:border-b-0 active:bg-gray-50"
                      onClick={() => handleSelectActivity(activity, 'departure')}
                    >
                      <View className="flex">
                        {activity.imageUrl && (
                          <Image
                            src={activity.imageUrl}
                            className="w-16 h-16 rounded-lg mr-4"
                            mode="aspectFill"
                          />
                        )}
                        <View className="flex-1">
                          <Text className="text-base font-medium text-gray-800 block">
                            {activity.name}
                          </Text>
                          <Text className="text-sm text-gray-500 mt-1 block">
                            {info.date}
                          </Text>
                          <Text className="text-sm text-gray-500 mt-1 block">
                            {info.location}
                          </Text>
                          {info.address && (
                            <Text className="text-xs text-gray-400 mt-1 block">
                              {info.address}
                            </Text>
                          )}
                          <Text className="text-sm text-blue-500 mt-2 block">
                            到达：{routeInfo.toCity}
                          </Text>
                        </View>
                        <View className="text-gray-400 text-lg">›</View>
                      </View>
                    </View>
                  )
                })}
              </View>
            ) : (
              <View className="bg-white rounded-b-lg border border-gray-200 p-8 text-center">
                <Text className="text-gray-500">{routeInfo.toCity}暂无活动</Text>
              </View>
            )}
          </View>

          {/* 返程活动区域 */}
          <View className="mb-6">
            <View className="bg-gradient-to-r from-green-500 to-green-600 rounded-t-lg p-4">
              <View className="flex items-center mb-1">
                <Text className="text-white text-lg mr-2">🏠</Text>
                <Text className="text-white text-lg font-bold">返程活动</Text>
              </View>
              <Text className="text-white/90 text-sm">
                从{routeInfo.fromCity}观看活动后返回
              </Text>
            </View>

            {returnActivities.length > 0 ? (
              <View className="bg-white rounded-b-lg border border-gray-200">
                {returnActivities.map(activity => {
                  const info = getActivityDisplayInfo(activity)
                  return (
                    <View
                      key={activity.id}
                      className="p-4 border-b border-gray-100 last:border-b-0 active:bg-gray-50"
                      onClick={() => handleSelectActivity(activity, 'return')}
                    >
                      <View className="flex">
                        {activity.imageUrl && (
                          <Image
                            src={activity.imageUrl}
                            className="w-16 h-16 rounded-lg mr-4"
                            mode="aspectFill"
                          />
                        )}
                        <View className="flex-1">
                          <Text className="text-base font-medium text-gray-800 block">
                            {activity.name}
                          </Text>
                          <Text className="text-sm text-gray-500 mt-1 block">
                            {info.date}
                          </Text>
                          <Text className="text-sm text-gray-500 mt-1 block">
                            {info.location}
                          </Text>
                          {info.address && (
                            <Text className="text-xs text-gray-400 mt-1 block">
                              {info.address}
                            </Text>
                          )}
                          <Text className="text-sm text-green-500 mt-2 block">
                            出发：{routeInfo.fromCity}
                          </Text>
                        </View>
                        <View className="text-gray-400 text-lg">›</View>
                      </View>
                    </View>
                  )
                })}
              </View>
            ) : (
              <View className="bg-white rounded-b-lg border border-gray-200 p-8 text-center">
                <Text className="text-gray-500">{routeInfo.fromCity}暂无活动</Text>
              </View>
            )}
          </View>

          {/* 全部为空的状态 */}
          {departureActivities.length === 0 && returnActivities.length === 0 && (
            <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">
                {routeInfo.fromCity}和{routeInfo.toCity}当前都没有热门活动
              </Text>
            </View>
          )}
        </View>
      </ScrollView>
    </View>
  )
}

export default ActivitySelectPage