import React, { useState } from 'react'
import { View, Text, Swiper, SwiperItem, Image, Button, Picker } from '@tarojs/components'
import { navigateTo } from '@tarojs/taro'
import { format } from 'date-fns'
import { zhCN } from 'date-fns/locale'
import { TabBarLayout } from '@/layouts/tab-bar-layout'
import { AreaPicker } from '../../components/AreaPicker'
import { Navbar } from '@/components/ui/navbar'
import banner1 from '../../../images/banner1.jpg'


interface SearchParams {
  startAreaIds?: number[]
  endAreaIds?: number[]
  date: string
  vehicleType: string
  travelMode: string
}

interface AreaInfo {
  id: number
  name: string
  type: 'province' | 'city' | 'district'
}

const HomePage: React.FC = () => {
  const [searchParams, setSearchParams] = useState<SearchParams>({
    date: new Date().toISOString().split('T')[0],
    vehicleType: 'bus',
    travelMode: 'carpool'
  })
  const [areaPickerVisible, setAreaPickerVisible] = useState(false)
  const [currentPickerType, setCurrentPickerType] = useState<'start' | 'end'>('start')
  const [areaData, setAreaData] = useState<AreaInfo[]>([])

  // 出行方式选项 - 组合查询映射
  const travelOptions = [
    {
      type: 'bus',
      name: '大巴拼车',
      vehicleType: 'bus',
      travelMode: 'carpool'
    },
    {
      type: 'business',
      name: '商务车',
      vehicleType: 'business',
      travelMode: 'carpool,charter' // 商务车支持拼车和包车
    },
    {
      type: 'charter',
      name: '包车',
      vehicleType: 'bus,business', // 包车支持大巴和商务车
      travelMode: 'charter'
    }
  ]

  // 固定轮播图（MVP阶段使用固定图片）
  const banners = [
    {
      id: 1,
      img: banner1,
      title: '便捷出行',
      subtitle: '专业出行服务，安全舒适'
    }
  ]

  // 打开地区选择器
  const openAreaPicker = (type: 'start' | 'end') => {
    setCurrentPickerType(type)
    setAreaPickerVisible(true)
  }

  // 关闭地区选择器
  const closeAreaPicker = () => {
    setAreaPickerVisible(false)
  }


  // 格式化日期显示
  const formatDateDisplay = (dateStr: string) => {
    const date = new Date(dateStr)
    return format(date, 'M月d日', { locale: zhCN })
  }

  // 处理日期选择
  const handleDateChange = (e: any) => {
    setSearchParams(prev => ({
      ...prev,
      date: e.detail.value
    }))
  }

  // 处理出行方式选择
  const handleTravelOptionChange = (option: typeof travelOptions[0]) => {
    setSearchParams(prev => ({
      ...prev,
      vehicleType: option.vehicleType,
      travelMode: option.travelMode
    }))
  }

  // 交换出发地和目的地
  const handleSwapLocations = () => {
    setSearchParams(prev => ({
      ...prev,
      startAreaIds: prev.endAreaIds,
      endAreaIds: prev.startAreaIds
    }))
  }

  // 查询路线
  const handleSearch = () => {
    // 验证必填字段
    if (!searchParams.startAreaIds?.length || !searchParams.endAreaIds?.length) {
      // 这里可以添加错误提示
      console.log('请选择出发地和目的地')
      return
    }

    // 获取地区显示文本
    const startAreaName = getAreaDisplayText(searchParams.startAreaIds)
    const endAreaName = getAreaDisplayText(searchParams.endAreaIds)

    // 导航到活动选择页面
    navigateTo({
      url: `/pages/select-activity/ActivitySelectPage?` +
        `startAreaIds=${JSON.stringify(searchParams.startAreaIds)}&` +
        `endAreaIds=${JSON.stringify(searchParams.endAreaIds)}&` +
        `startAreaName=${encodeURIComponent(startAreaName)}&` +
        `endAreaName=${encodeURIComponent(endAreaName)}&` +
        `date=${searchParams.date}&` +
        `vehicleType=${searchParams.vehicleType}&` +
        `travelMode=${searchParams.travelMode}`
    })
  }

  // 获取地区显示文本
  const getAreaDisplayText = (areaIds?: number[]) => {
    if (!areaIds || areaIds.length === 0) return '请选择地区'

    // 根据areaIds获取地区名称
    const areaNames = areaIds.map(id => {
      const area = areaData.find(a => a.id === id)
      return area ? area.name : '未知地区'
    })

    return areaNames.join(' ') || '请选择地区'
  }

  // 获取出行方式样式
  const getVehicleTypeStyle = (type: string) => {
    switch (type) {
      case 'bus':
        return 'bg-gradient-to-r from-primary to-primary-dark shadow-primary'
      case 'business':
        return 'bg-gradient-to-r from-secondary to-primary shadow-medium'
      case 'charter':
        return 'bg-gradient-to-r from-charter to-charter-light shadow-charter'
      default:
        return 'bg-gradient-to-r from-primary to-primary-dark shadow-primary'
    }
  }

  // 当地区选择确认时，存储地区数据
  const handleAreaConfirm = (areaIds: number[], areaInfos: AreaInfo[]) => {
    // 更新地区数据
    setAreaData(prev => {
      const filtered = prev.filter(a => !areaIds.includes(a.id))
      return [...filtered, ...areaInfos]
    })

    if (currentPickerType === 'start') {
      setSearchParams(prev => ({
        ...prev,
        startAreaIds: areaIds
      }))
    } else {
      setSearchParams(prev => ({
        ...prev,
        endAreaIds: areaIds
      }))
    }
    closeAreaPicker()
  }

  return (
    <TabBarLayout activeKey="home" className="bg-gradient-to-b from-primary to-primary-dark">
      {/* 导航栏 */}
      <Navbar
        title="去看出行"
        backgroundColor="bg-primary"
        textColor="text-white"
        leftIcon=""
        border={false}
      />

      {/* 顶部轮播图 */}
      <View className="h-64 w-full">
        <Swiper
          className="w-full h-full"
          autoplay
          interval={5000}
          circular
          indicatorDots
        >
          {banners.map(banner => (
            <SwiperItem key={banner.id}>
              <View className="relative w-full h-full">
                <Image
                  src={banner.img}
                  className="w-full h-full"
                  mode="aspectFill"
                />
                <View className="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/70 to-transparent p-4">
                  <Text className="text-white text-lg font-bold block">
                    {banner.title}
                  </Text>
                  {banner.subtitle && (
                    <Text className="text-white/90 text-sm block mt-1">
                      {banner.subtitle}
                    </Text>
                  )}
                </View>
              </View>
            </SwiperItem>
          ))}
        </Swiper>
      </View>

      {/* 出行方式选择 */}
      <View className="mx-4 mt-4 bg-white/95 rounded-button p-1 shadow-medium">
        <View className="flex">
          {travelOptions.map(option => (
            <View
              key={option.type}
              className={`flex-1 text-center py-2 rounded-button transition-all duration-300 ${
                searchParams.vehicleType === option.vehicleType && searchParams.travelMode === option.travelMode
                  ? getVehicleTypeStyle(option.type) + ' text-white font-bold'
                  : 'text-gray-600'
              }`}
              onClick={() => handleTravelOptionChange(option)}
            >
              <Text className="text-sm">{option.name}</Text>
            </View>
          ))}
        </View>
      </View>

      {/* 出行选择区域 */}
      <View className="mx-4 mt-4 bg-white/95 rounded-card p-card shadow-medium">
        {/* 出发地和目的地选择 - 紧凑布局 */}
        <View className="flex items-center gap-4 mb-4">
          {/* 出发地选择按钮 */}
          <View className="flex-1">
            <Button
              className="bg-gray-50 border border-gray-300 rounded-lg p-3 text-left w-full"
              onClick={() => openAreaPicker('start')}
            >
              <Text className="text-sm text-gray-600 block">出发地</Text>
              <Text className="text-sm font-medium text-gray-800 block mt-1">
                {getAreaDisplayText(searchParams.startAreaIds)}
              </Text>
            </Button>
          </View>

          {/* 交换按钮 */}
          <Button
            className="bg-gradient-to-r from-primary to-primary-dark text-white rounded-button w-10 h-10 flex items-center justify-center shadow-primary"
            onClick={handleSwapLocations}
          >
            <Text className="text-lg font-bold">⇄</Text>
          </Button>

          {/* 目的地选择按钮 */}
          <View className="flex-1">
            <Button
              className="bg-gray-50 border border-gray-300 rounded-lg p-3 text-left w-full"
              onClick={() => openAreaPicker('end')}
            >
              <Text className="text-sm text-gray-600 block">目的地</Text>
              <Text className="text-sm font-medium text-gray-800 block mt-1">
                {getAreaDisplayText(searchParams.endAreaIds)}
              </Text>
            </Button>
          </View>
        </View>

        {/* 日期选择 */}
        <View className="mt-4">
          <Text className="text-sm text-gray-600 mb-2 block">出发日期</Text>
          <View className="flex justify-between items-center bg-gray-50 rounded-lg p-3 border border-gray-200">
            <Text className="text-sm text-gray-600">选择日期</Text>
            <Picker
              mode="date"
              value={searchParams.date}
              start={new Date().toISOString().split('T')[0]}
              end={new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString().split('T')[0]}
              fields="day"
              onChange={handleDateChange}
            >
              <View className="picker-trigger bg-white px-3 py-1 rounded-small border border-gray-300">
                <Text className="text-sm text-primary font-bold">
                  {formatDateDisplay(searchParams.date)}
                </Text>
              </View>
            </Picker>
          </View>
        </View>

        {/* 查询按钮 */}
        <Button
          className="w-4/5 mx-auto mt-6 bg-gradient-to-r from-primary to-primary-dark text-white border-none rounded-button py-button text-base font-bold shadow-primary"
          onClick={handleSearch}
        >
          查询路线
        </Button>
      </View>

      {/* MVP限制说明 - 热门路线不实现 */}
      <View className="mx-4 mt-4 bg-white/95 rounded-card p-card shadow-light">
        <Text className="text-sm text-gray-500 text-center">
          更多功能正在开发中...
        </Text>
      </View>

      {/* 地区选择器弹出层 */}
      <AreaPicker
        visible={areaPickerVisible}
        onClose={closeAreaPicker}
        onConfirm={handleAreaConfirm}
        value={currentPickerType === 'start' ? searchParams.startAreaIds : searchParams.endAreaIds}
        title={currentPickerType === 'start' ? '选择出发地' : '选择目的地'}
      />
    </TabBarLayout>
  )
}

export default HomePage;