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

interface Area {
  id: number
  name: string
  level: number
  parentId?: number
}

interface AreaCascaderProps {
  value?: number[]
  onChange?: (value: number[]) => void
  placeholder?: string
}

export const AreaCascader: React.FC<AreaCascaderProps> = ({
  value = [],
  onChange,
  placeholder = '请选择省市区'
}) => {
  const [selectedProvince, setSelectedProvince] = useState<number | undefined>(value[0])
  const [selectedCity, setSelectedCity] = useState<number | undefined>(value[1])
  const [selectedDistrict, setSelectedDistrict] = useState<number | undefined>(value[2])

  // 获取省份列表
  const { data: provinces = [] } = useQuery({
    queryKey: ['areas', 'provinces'],
    queryFn: async () => {
      const res = await areaClient.provinces.$get()
      if (res.status !== 200) throw new Error('获取省份列表失败')
      return await res.json()
    }
  })

  // 获取城市列表
  const { data: cities = [] } = useQuery({
    queryKey: ['areas', 'cities', selectedProvince],
    queryFn: async () => {
      if (!selectedProvince) return []
      const res = await areaClient.cities.$get({
        query: { provinceId: selectedProvince }
      })
      if (res.status !== 200) throw new Error('获取城市列表失败')
      return await res.json()
    },
    enabled: !!selectedProvince
  })

  // 获取区县列表
  const { data: districts = [] } = useQuery({
    queryKey: ['areas', 'districts', selectedCity],
    queryFn: async () => {
      if (!selectedCity) return []
      const res = await areaClient.districts.$get({
        query: { cityId: selectedCity }
      })
      if (res.status !== 200) throw new Error('获取区县列表失败')
      return await res.json()
    },
    enabled: !!selectedCity
  })

  // 处理省份选择
  const handleProvinceChange = (e: any) => {
    const provinceId = Number(e.detail.value)
    setSelectedProvince(provinceId)
    setSelectedCity(undefined)
    setSelectedDistrict(undefined)

    if (onChange) {
      onChange([provinceId])
    }
  }

  // 处理城市选择
  const handleCityChange = (e: any) => {
    const cityId = Number(e.detail.value)
    setSelectedCity(cityId)
    setSelectedDistrict(undefined)

    if (onChange && selectedProvince) {
      onChange([selectedProvince, cityId])
    }
  }

  // 处理区县选择
  const handleDistrictChange = (e: any) => {
    const districtId = Number(e.detail.value)
    setSelectedDistrict(districtId)

    if (onChange && selectedProvince && selectedCity) {
      onChange([selectedProvince, selectedCity, districtId])
    }
  }

  // 获取显示文本
  const getDisplayText = () => {
    if (!selectedProvince) return placeholder

    const province = provinces.find(p => p.id === selectedProvince)
    const city = cities.find(c => c.id === selectedCity)
    const district = districts.find(d => d.id === selectedDistrict)

    if (district && city && province) {
      return `${province.name} ${city.name} ${district.name}`
    } else if (city && province) {
      return `${province.name} ${city.name}`
    } else if (province) {
      return province.name
    }

    return placeholder
  }

  return (
    <View className="flex flex-col space-y-2">
      <View className="flex space-x-2">
        {/* 省份选择器 */}
        <View className="flex-1">
          <Text className="text-sm text-gray-600 mb-1 block">省份</Text>
          <Picker
            mode="selector"
            range={provinces}
            rangeKey="name"
            value={selectedProvince ? provinces.findIndex(p => p.id === selectedProvince) : 0}
            onChange={handleProvinceChange}
          >
            <View className="border border-gray-300 rounded px-3 py-2 text-sm">
              {selectedProvince ? provinces.find(p => p.id === selectedProvince)?.name : '请选择省份'}
            </View>
          </Picker>
        </View>

        {/* 城市选择器 */}
        <View className="flex-1">
          <Text className="text-sm text-gray-600 mb-1 block">城市</Text>
          <Picker
            mode="selector"
            range={cities}
            rangeKey="name"
            value={selectedCity ? cities.findIndex(c => c.id === selectedCity) : 0}
            onChange={handleCityChange}
            disabled={!selectedProvince}
          >
            <View className={`border border-gray-300 rounded px-3 py-2 text-sm ${!selectedProvince ? 'bg-gray-100 text-gray-400' : ''}`}>
              {selectedCity ? cities.find(c => c.id === selectedCity)?.name : '请选择城市'}
            </View>
          </Picker>
        </View>

        {/* 区县选择器 */}
        <View className="flex-1">
          <Text className="text-sm text-gray-600 mb-1 block">区县</Text>
          <Picker
            mode="selector"
            range={districts}
            rangeKey="name"
            value={selectedDistrict ? districts.findIndex(d => d.id === selectedDistrict) : 0}
            onChange={handleDistrictChange}
            disabled={!selectedCity}
          >
            <View className={`border border-gray-300 rounded px-3 py-2 text-sm ${!selectedCity ? 'bg-gray-100 text-gray-400' : ''}`}>
              {selectedDistrict ? districts.find(d => d.id === selectedDistrict)?.name : '请选择区县'}
            </View>
          </Picker>
        </View>
      </View>

      {/* 显示完整选择路径 */}
      <View className="text-sm text-gray-500">
        {getDisplayText()}
      </View>
    </View>
  )
}