import {useState, useEffect, useCallback} from 'react'
import Taro, { useDidShow } from '@tarojs/taro'
import {getShopDealerUser} from '@/api/shop/shopDealerUser'
import type {ShopDealerUser} from '@/api/shop/shopDealerUser/model'

// Hook 返回值接口
export interface UseDealerUserReturn {
  // 经销商用户信息
  dealerUser: ShopDealerUser | null
  // 加载状态
  loading: boolean
  // 错误信息
  error: string | null
  // 刷新数据
  refresh: () => Promise<void>
}


/**
 * 经销商用户 Hook - 简化版本
 * 只查询经销商用户信息和判断是否存在
 */
export const useDealerUser = (): UseDealerUserReturn => {
  const [dealerUser, setDealerUser] = useState<ShopDealerUser | null>(null)
  const rawUserId = Taro.getStorageSync('UserId')
  const userId = Number(rawUserId)
  const hasUser = Number.isFinite(userId) && userId > 0

  // If user is logged in, start in loading state to avoid "click too fast" mis-routing.
  const [loading, setLoading] = useState<boolean>(hasUser)
  const [error, setError] = useState<string | null>(null)

  // 获取经销商用户数据
  const fetchDealerData = useCallback(async () => {

    if (!hasUser) {
      setDealerUser(null)
      setLoading(false)
      return
    }

    try {
      setLoading(true)
      setError(null)

      // 查询当前用户的经销商信息
      const dealer = await getShopDealerUser(userId)

      if (dealer) {
        setDealerUser(dealer)
      } else {
        setDealerUser(null)
      }
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : '获取经销商信息失败'
      setError(errorMessage)
      setDealerUser(null)
    } finally {
      setLoading(false)
    }
  }, [hasUser, userId])

  // 刷新数据
  const refresh = useCallback(async () => {
    await fetchDealerData()
  }, [fetchDealerData])

  // 初始化加载数据
  useEffect(() => {
    if (hasUser) {
      fetchDealerData()
    } else {
      setDealerUser(null)
      setError(null)
      setLoading(false)
    }
  }, [fetchDealerData, hasUser])

  // 页面返回/切换到前台时刷新一次，避免“注册成为经销商后，页面不更新”
  useDidShow(() => {
    fetchDealerData()
  })

  // 允许业务侧通过事件主动触发刷新（例如：注册成功后触发）
  useEffect(() => {
    const handler = () => {
      fetchDealerData()
    }
    // 事件名尽量语义化；后续可在注册成功处 trigger
    Taro.eventCenter.on('dealerUser:changed', handler)
    return () => {
      Taro.eventCenter.off('dealerUser:changed', handler)
    }
  }, [fetchDealerData])

  return {
    dealerUser,
    loading,
    error,
    refresh
  }
}
