import React, { useState, useEffect, useRef } from 'react'
import { View, Text, ScrollView, Input } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { listShopStore } from '@/api/shop/shopStore'
import type { ShopStore } from '@/api/shop/shopStore/model'
import EmptyState from '@/components/common/EmptyState'
import { useScrollHeight } from '@/hooks/useScrollHeight'

definePageConfig({
  navigationBarTitleText: '门店列表',
})

/** 两点间距离（km），使用 Haversine 公式 */
function calcDistance(lat1: number, lng1: number, lat2: number, lng2: number) {
  const R = 6371
  const dLat = ((lat2 - lat1) * Math.PI) / 180
  const dLng = ((lng2 - lng1) * Math.PI) / 180
  const a =
    Math.sin(dLat / 2) * Math.sin(dLat / 2) +
    Math.cos((lat1 * Math.PI) / 180) *
      Math.cos((lat2 * Math.PI) / 180) *
      Math.sin(dLng / 2) *
      Math.sin(dLng / 2)
  return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
}

/** 格式化距离显示 */
function formatDistance(km: number) {
  return km < 1 ? `${Math.round(km * 1000)}m` : `${km.toFixed(1)}km`
}

const StoreListPage: React.FC = () => {
  const params = Taro.getCurrentInstance().router?.params || {}
  // selectMode=1 时表示从预约页跳来，选中后回传
  const selectMode = params.selectMode === '1'

  const [stores, setStores] = useState<ShopStore[]>([])
  const [loading, setLoading] = useState(true)
  const [locating, setLocating] = useState(false)
  const [hasLocation, setHasLocation] = useState(false)
  const [searchKeyword, setSearchKeyword] = useState('')
  const scrollHeight = useScrollHeight(44)
  const searchTimer = useRef<any>(null)
  const myLocation = useRef<{ lat: number; lng: number } | null>(null)
  const locationError = useRef(false)

  useEffect(() => {
    getLocation()
  }, [])

  useEffect(() => {
    // 搜索防抖 500ms
    if (searchTimer.current) clearTimeout(searchTimer.current)
    searchTimer.current = setTimeout(() => {
      fetchStores()
    }, 500)
    return () => clearTimeout(searchTimer.current)
  }, [searchKeyword])

  /** 获取当前定位，用于计算距离 */
  const getLocation = () => {
    setLocating(true)
    locationError.current = false
    Taro.getLocation({
      type: 'gcj02',
      success: (res) => {
        myLocation.current = { lat: res.latitude, lng: res.longitude }
        setHasLocation(true)
        fetchStores(res.latitude, res.longitude)
      },
      fail: (err) => {
        console.error('定位失败:', err)
        locationError.current = true
        setHasLocation(false)
        // 用户拒绝授权时引导去设置页
        if (err.errMsg && err.errMsg.includes('auth deny')) {
          Taro.showModal({
            title: '定位授权',
            content: '需要获取您的位置信息才能按距离排序门店，是否去设置页开启定位权限？',
            confirmText: '去设置',
            success: (modalRes) => {
              if (modalRes.confirm) {
                Taro.openSetting()
              }
            },
          })
        }
        fetchStores()
      },
      complete: () => {
        setLocating(false)
      },
    })
  }

  const fetchStores = async (lat?: number, lng?: number) => {
    try {
      setLoading(true)
      const reqParams: any = { status: 1 }
      if (searchKeyword.trim()) {
        reqParams.keywords = searchKeyword.trim()
      }
      const data = await listShopStore(reqParams)
      let list = data || []

      // 计算距离
      const userLat = lat ?? myLocation.current?.lat
      const userLng = lng ?? myLocation.current?.lng
      if (userLat && userLng) {
        list = list
          .map((store) => {
            if (store.lngAndLat) {
              const parts = store.lngAndLat.split(',')
              if (parts.length === 2) {
                const sLng = parseFloat(parts[0])
                const sLat = parseFloat(parts[1])
                if (sLat && sLng) {
                  return { ...store, distance: calcDistance(userLat, userLng, sLat, sLng) }
                }
              }
            }
            return store
          })
          .sort((a, b) => {
            if (a.distance == null && b.distance == null) return 0
            if (a.distance == null) return 1
            if (b.distance == null) return -1
            return a.distance - b.distance
          })
      }

      setStores(list)
    } catch (e) {
      console.error('获取门店列表失败:', e)
    } finally {
      setLoading(false)
    }
  }

  const handleSearch = (e: any) => {
    setSearchKeyword(e.detail.value || '')
  }

  const clearSearch = () => {
    setSearchKeyword('')
  }

  const handleCallStore = (phone: string) => {
    if (!phone) {
      Taro.showToast({ title: '暂无联系电话', icon: 'none' })
      return
    }
    Taro.makePhoneCall({
      phoneNumber: phone,
      fail: () => {
        Taro.showToast({ title: '拨打失败', icon: 'none' })
      },
    })
  }

  const handleOpenMap = (store: ShopStore) => {
    if (!store.lngAndLat) {
      Taro.showToast({ title: '暂无位置信息', icon: 'none' })
      return
    }
    const parts = store.lngAndLat.split(',')
    if (parts.length !== 2) {
      Taro.showToast({ title: '位置信息格式有误', icon: 'none' })
      return
    }
    const longitude = parseFloat(parts[0])
    const latitude = parseFloat(parts[1])
    if (!latitude || !longitude) {
      Taro.showToast({ title: '暂无位置信息', icon: 'none' })
      return
    }
    Taro.openLocation({
      latitude,
      longitude,
      name: store.name || '',
      address: store.address || '',
    })
  }

  const handleBooking = (store: ShopStore) => {
    if (selectMode) {
      // 选择模式：将门店信息回传给上一页
      const pages = Taro.getCurrentPages()
      const prevPage = pages[pages.length - 2]
      if (prevPage) {
        ;(prevPage as any).setSelectedStore?.(store)
      }
      Taro.navigateBack()
    } else {
      Taro.navigateTo({ url: `/pages/store/booking/index?storeId=${store.id}` })
    }
  }

  return (
    <View className='min-h-screen bg-gray-50'>
      {/* 搜索框 + 定位按钮 */}
      <View className='bg-white px-3 py-3 sticky top-0 z-10'>
        <View className='flex items-center gap-2'>
          <View className='flex-1 flex items-center bg-gray-100 rounded-lg px-3 py-2'>
            <Text className='text-gray-400 mr-2'>🔍</Text>
            <Input
              value={searchKeyword}
              onInput={handleSearch}
              placeholder='搜索门店名称'
              className='flex-1 text-sm'
            />
            {searchKeyword && (
              <View onClick={clearSearch}>
                <Text className='text-gray-400 text-sm'>✕</Text>
              </View>
            )}
          </View>
          <View
            className='flex items-center justify-center bg-green-50 rounded-lg px-3 py-2'
            onClick={getLocation}
          >
            <Text className='text-xs text-green-600'>{locating ? '定位中' : '📡 定位'}</Text>
          </View>
        </View>
        {selectMode && (
          <Text className='text-xs text-gray-400 mt-2 block'>请选择预约门店</Text>
        )}

        {/* 排序 / 距离提示条 */}
        {!loading && stores.length > 0 && (
          <View className='flex items-center justify-between mt-2 pt-2 border-t border-gray-50'>
            {hasLocation ? (
              <View className='flex items-center gap-1'>
                <Text className='text-xs text-green-500'>📍</Text>
                <Text className='text-xs text-green-500'>已按距离由近到远排序</Text>
              </View>
            ) : locating ? (
              <View className='flex items-center gap-1'>
                <Text className='text-xs text-gray-400'>⏳</Text>
                <Text className='text-xs text-gray-400'>正在获取位置...</Text>
              </View>
            ) : (
              <View className='flex items-center gap-1'>
                <Text className='text-xs text-gray-400'>📌</Text>
                <Text className='text-xs text-gray-400'>未获取位置</Text>
              </View>
            )}
            {!hasLocation && !locating && (
              <View
                className='px-2 py-1 bg-green-50 rounded'
                onClick={getLocation}
              >
                <Text className='text-xs text-green-600'>重新定位</Text>
              </View>
            )}
          </View>
        )}
      </View>

      <ScrollView scrollY style={{ height: scrollHeight }}>
        {loading ? (
          <View className='flex items-center justify-center py-10'>
            <Text className='text-gray-400'>加载中...</Text>
          </View>
        ) : stores.length === 0 ? (
          <EmptyState text='暂无门店' />
        ) : (
          <View className='p-3'>
            {stores.map((store) => (
              <View key={store.id} className='bg-white rounded-xl p-4 mb-3 shadow-sm'>
                {/* 门店名 + 距离 */}
                <View className='flex justify-between items-start mb-2'>
                  <Text className='text-base font-semibold text-gray-800 flex-1 mr-2'>
                    {store.name}
                  </Text>
                  {store.distance != null && (
                    <Text className='text-xs text-green-500 shrink-0'>
                      {formatDistance(store.distance)}
                    </Text>
                  )}
                </View>

                {/* 地址 */}
                <View
                  className='flex items-start mb-1'
                  onClick={() => handleOpenMap(store)}
                >
                  <Text className='text-xs text-blue-400 mr-1 shrink-0'>📍</Text>
                  <Text className='text-xs text-blue-500 flex-1 underline'>
                    {store.address || '暂无地址'}
                  </Text>
                </View>

                {/* 营业时间 */}
                {store.businessHours ? (
                  <View className='flex items-center mb-1'>
                    <Text className='text-xs text-gray-400 mr-1 shrink-0'>🕐</Text>
                    <Text className='text-xs text-gray-500'>{store.businessHours}</Text>
                  </View>
                ) : (
                  <View className='flex items-center mb-1'>
                    <Text className='text-xs text-gray-400 mr-1 shrink-0'>🕐</Text>
                    <Text className='text-xs text-gray-400'>营业时间：9:00 ~ 18:00</Text>
                  </View>
                )}

                {/* 操作按钮 */}
                <View className='flex gap-2 mt-3'>
                  <View
                    className='flex-1 py-2 bg-blue-50 rounded-lg text-center'
                    onClick={() => handleCallStore(store.phone || '')}
                  >
                    <Text className='text-xs text-blue-500'>📞 拨打电话</Text>
                  </View>
                  <View
                    className='flex-1 py-2 bg-gray-50 rounded-lg text-center'
                    onClick={() => handleOpenMap(store)}
                  >
                    <Text className='text-xs text-gray-500'>🗺 查看地图</Text>
                  </View>
                  {/*<View*/}
                  {/*  className='flex-1 py-2 rounded-lg text-center'*/}
                  {/*  style={{ background: selectMode ? '#0e932e' : '#fff7ed', border: selectMode ? 'none' : '1px solid #fed7aa' }}*/}
                  {/*  onClick={() => handleBooking(store)}*/}
                  {/*>*/}
                  {/*  <Text className={`text-xs ${selectMode ? 'text-white' : 'text-orange-500'}`}>*/}
                  {/*    {selectMode ? '✓ 选择' : '📅 立即预约'}*/}
                  {/*  </Text>*/}
                  {/*</View>*/}
                </View>
              </View>
            ))}
          </View>
        )}
      </ScrollView>
    </View>
  )
}

export default StoreListPage
