import React, { useState, useEffect } from 'react'
import { View, Text, Swiper, SwiperItem, Image, Button } from '@tarojs/components'
import { navigateTo } from '@tarojs/taro'
import { TabBarLayout } from '@/layouts/tab-bar-layout'
import { AreaPicker } from '../../components/AreaPicker'
import banner1 from '../../../images/banner1.jpg'


interface SearchParams {
  startAreaIds?: number[]
  endAreaIds?: number[]
  date: string
  vehicleType: 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'
  })
  const [areaPickerVisible, setAreaPickerVisible] = useState(false)
  const [currentPickerType, setCurrentPickerType] = useState<'start' | 'end'>('start')
  const [areaData, setAreaData] = useState<AreaInfo[]>([])

  // 出行方式选项
  const vehicleTypes = [
    { type: 'bus', name: '大巴拼车' },
    { type: 'business', name: '商务车' },
    { type: 'charter', name: '包车' }
  ]

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

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

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


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

  // 处理出行方式选择
  const handleVehicleTypeChange = (type: string) => {
    setSearchParams(prev => ({
      ...prev,
      vehicleType: type
    }))
  }

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

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

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

  // 获取地区显示文本
  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 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-blue-500 to-blue-600">
      {/* 顶部轮播图 */}
      <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-full p-1 shadow-lg">
        <View className="flex">
          {vehicleTypes.map(type => (
            <View
              key={type.type}
              className={`flex-1 text-center py-2 rounded-full transition-all duration-300 ${
                searchParams.vehicleType === type.type
                  ? 'bg-blue-500 text-white font-bold shadow-md'
                  : 'text-gray-600'
              }`}
              onClick={() => handleVehicleTypeChange(type.type)}
            >
              <Text className="text-sm">{type.name}</Text>
            </View>
          ))}
        </View>
      </View>

      {/* 出行选择区域 */}
      <View className="mx-4 mt-4 bg-white/95 rounded-xl p-4 shadow-lg">
        {/* 出发地和目的地选择 - 紧凑布局 */}
        <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-blue-500 text-white rounded-full w-10 h-10 flex items-center justify-center shadow-md"
            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>
            <View className="picker">
              <input
                type="date"
                value={searchParams.date}
                onChange={handleDateChange}
                className="text-sm text-blue-500 font-bold"
              />
            </View>
          </View>
        </View>

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

      {/* MVP限制说明 - 热门路线不实现 */}
      <View className="mx-4 mt-4 bg-white/95 rounded-xl p-4 shadow-lg">
        <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;