import React, { useState, useEffect } from 'react'
import { View, Text, Input, ScrollView } from '@tarojs/components'
import { useQuery } from '@tanstack/react-query'
import { locationClient } from '../api'

interface Location {
  id: number
  name: string
  province?: string
  city?: string
  district?: string
  address?: string
}

interface LocationSearchProps {
  value?: Location | null
  onChange?: (location: Location | null) => void
  placeholder?: string
  areaFilter?: {
    provinceId?: number
    cityId?: number
    districtId?: number
  }
}

export const LocationSearch: React.FC<LocationSearchProps> = ({
  value,
  onChange,
  placeholder = '搜索地点',
  areaFilter = {}
}) => {
  const [keyword, setKeyword] = useState('')
  const [showResults, setShowResults] = useState(false)
  const [debouncedKeyword, setDebouncedKeyword] = useState('')

  // 防抖处理
  useEffect(() => {
    const timer = setTimeout(() => {
      setDebouncedKeyword(keyword)
    }, 300)

    return () => clearTimeout(timer)
  }, [keyword])

  // 搜索地点
  const { data: locations = [], isLoading } = useQuery({
    queryKey: ['locations', debouncedKeyword, areaFilter],
    queryFn: async () => {
      if (!debouncedKeyword.trim()) return []

      const res = await locationClient.$get({
        query: {
          keyword: debouncedKeyword,
          provinceId: areaFilter.provinceId,
          cityId: areaFilter.cityId,
          districtId: areaFilter.districtId
        }
      })
      if (res.status !== 200) throw new Error('搜索地点失败')
      return await res.json()
    },
    enabled: !!debouncedKeyword.trim()
  })

  // 处理输入变化
  const handleInputChange = (e: any) => {
    const value = e.detail.value
    setKeyword(value)
    if (value) {
      setShowResults(true)
    } else {
      setShowResults(false)
    }
  }

  // 选择地点
  const handleSelectLocation = (location: Location) => {
    setKeyword(location.name)
    setShowResults(false)
    if (onChange) {
      onChange(location)
    }
  }

  // 清除选择
  const handleClear = () => {
    setKeyword('')
    setShowResults(false)
    if (onChange) {
      onChange(null)
    }
  }

  // 获取显示文本
  const getDisplayText = (location: Location) => {
    const parts = [location.name]
    if (location.district) parts.push(location.district)
    if (location.city) parts.push(location.city)
    if (location.province) parts.push(location.province)

    return parts.join(' · ')
  }

  return (
    <View className="relative">
      {/* 搜索输入框 */}
      <View className="relative">
        <Input
          type="text"
          value={keyword}
          placeholder={placeholder}
          onInput={handleInputChange}
          onFocus={() => {
            if (keyword && locations.length > 0) {
              setShowResults(true)
            }
          }}
          className="border border-gray-300 rounded px-3 py-2 text-sm w-full"
        />

        {/* 清除按钮 */}
        {keyword && (
          <View
            className="absolute right-2 top-1/2 transform -translate-y-1/2 text-gray-400 text-lg"
            onClick={handleClear}
          >
            ×
          </View>
        )}
      </View>

      {/* 搜索结果 */}
      {showResults && (
        <View className="absolute top-full left-0 right-0 bg-white border border-gray-300 rounded shadow-lg z-10 max-h-60 overflow-y-auto">
          {isLoading ? (
            <View className="px-3 py-2 text-sm text-gray-500">搜索中...</View>
          ) : locations.length === 0 ? (
            <View className="px-3 py-2 text-sm text-gray-500">
              {debouncedKeyword ? '未找到相关地点' : '请输入地点名称'}
            </View>
          ) : (
            <ScrollView scrollY className="max-h-60">
              {locations.map((location: Location) => (
                <View
                  key={location.id}
                  className="px-3 py-2 border-b border-gray-100 hover:bg-gray-50 active:bg-gray-100"
                  onClick={() => handleSelectLocation(location)}
                >
                  <Text className="text-sm font-medium">{location.name}</Text>
                  {location.address && (
                    <Text className="text-xs text-gray-500 block mt-1">
                      {location.address}
                    </Text>
                  )}
                  {(location.province || location.city || location.district) && (
                    <Text className="text-xs text-gray-400 block">
                      {getDisplayText(location)}
                    </Text>
                  )}
                </View>
              ))}
            </ScrollView>
          )}
        </View>
      )}

      {/* 当前选择显示 */}
      {value && !keyword && (
        <View className="mt-2 p-2 bg-blue-50 rounded border border-blue-200">
          <Text className="text-sm text-blue-800">已选择: {getDisplayText(value)}</Text>
        </View>
      )}
    </View>
  )
}