import React from 'react'
import { View, Text, Image, ScrollView } 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 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[] : [],
    startAreaName: router.params.startAreaName ? decodeURIComponent(router.params.startAreaName) : '',
    endAreaName: router.params.endAreaName ? decodeURIComponent(router.params.endAreaName) : '',
    date: router.params.date || new Date().toISOString().split('T')[0],
    vehicleType: router.params.vehicleType || 'bus',
    travelMode: router.params.travelMode || 'carpool'
  }

  // 查询路线和关联活动
  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,
          vehicleType: searchParams.vehicleType,
          travelMode: searchParams.travelMode,
          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 getAreaNames = () => {
    // 如果路由参数中已经有地区名称，直接使用
    if (searchParams.startAreaName && searchParams.startAreaName !== '请选择地区' &&
        searchParams.endAreaName && searchParams.endAreaName !== '请选择地区') {
      return {
        startAreaName: searchParams.startAreaName,
        endAreaName: searchParams.endAreaName
      }
    }

    // 如果没有路线数据，使用默认值
    if (!routeData?.routes || routeData.routes.length === 0) {
      return {
        startAreaName: searchParams.startAreaName || '出发地',
        endAreaName: searchParams.endAreaName || '目的地'
      }
    }

    // 从第一条路线中获取出发地和目的地的地区信息
    const firstRoute = routeData.routes[0]
    const startLocation = firstRoute.startLocation
    const endLocation = firstRoute.endLocation

    const getAreaDisplayName = (location: any) => {
      if (!location) return ''

      // 显示完整的省市区信息
      const parts: string[] = []
      if (location.province?.name) {
        parts.push(location.province.name)
      }
      if (location.city?.name) {
        parts.push(location.city.name)
      }
      if (location.district?.name) {
        parts.push(location.district.name)
      }

      // 如果都没有，则使用location.name
      if (parts.length === 0 && location.name) {
        parts.push(location.name)
      }

      return parts.join('') || ''
    }

    return {
      startAreaName: getAreaDisplayName(startLocation) || searchParams.startAreaName || '出发地',
      endAreaName: getAreaDisplayName(endLocation) || searchParams.endAreaName || '目的地'
    }
  }

  const areaNames = getAreaNames()

  // 分离去程和返程活动
  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}&` +
        `travelMode=${searchParams.travelMode}&` +
        `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: format(new Date(activity.startDate), 'yyyy-MM-dd', { locale: zhCN })
    }
  }

  // 使用获取到的地区名称
  const routeInfo = {
    fromCity: areaNames.startAreaName,
    toCity: areaNames.endAreaName
  }

  if (isLoading) {
    return (
      <View className="min-h-screen bg-gray-50 flex items-center justify-center">
        <View className="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>
    )
  }

  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-4">
        <Text className="text-lg font-bold text-white block">
          {routeInfo.fromCity} → {routeInfo.toCity}
        </Text>
        <Text className="text-sm text-white/90 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-white rounded-card border border-gray-200 shadow-light overflow-hidden">
              <View className="bg-gradient-to-r from-primary to-primary-dark p-card">
                <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 ? (
                departureActivities.map(activity => {
                  const info = getActivityDisplayInfo(activity)
                  return (
                    <View
                      key={activity.id}
                      className="p-card 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-medium 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-primary mt-2 block">
                            到达：{routeInfo.toCity}
                          </Text>
                        </View>
                        <View className="text-gray-400 text-lg">›</View>
                      </View>
                    </View>
                  )
                })
              ) : (
                <View className="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.toCity}当前没有相关活动</Text>
                </View>
              )}
            </View>
          </View>

          {/* 返程活动区域 */}
          <View className="mb-6">
            <View className="bg-white rounded-card border border-gray-200 shadow-light overflow-hidden">
              <View className="bg-gradient-to-r from-charter-dark to-charter-bg p-card">
                <View className="flex items-center mb-1">
                  <Text className="text-charter text-lg mr-2">🏠</Text>
                  <Text className="text-charter text-lg font-bold">返程活动</Text>
                </View>
                <Text className="text-charter/90 text-sm">
                  从{routeInfo.fromCity}观看活动后返回
                </Text>
              </View>

              {returnActivities.length > 0 ? (
                returnActivities.map(activity => {
                  const info = getActivityDisplayInfo(activity)
                  return (
                    <View
                      key={activity.id}
                      className="p-card 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-medium 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-charter mt-2 block">
                            出发：{routeInfo.fromCity}
                          </Text>
                        </View>
                        <View className="text-gray-400 text-lg">›</View>
                      </View>
                    </View>
                  )
                })
              ) : (
                <View className="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}当前没有相关活动</Text>
                </View>
              )}
            </View>
          </View>

        </View>
      </ScrollView>
    </View>
  )
}

export default ActivitySelectPage