'use client'

import { createClient } from '@/lib/supabase'
import { User } from '@supabase/supabase-js'
import { useEffect, useState, useCallback, useRef } from 'react'
import { userCache, UserData, SyncTrigger, SyncOptions, shouldSync } from '@/lib/user-cache'

interface AuthUserState {
  user: User | null
  userData: UserData | null
  loading: boolean
  isAdmin: boolean
}

export function useAuthUser() {
  const [state, setState] = useState<AuthUserState>({
    user: null,
    userData: null,
    loading: true,
    isAdmin: false,
  })

  const supabase = createClient()
  const isInitializedRef = useRef(false)
  const currentUserIdRef = useRef<string | null>(null)

  // 同步用户数据到数据库
  const syncUserToDatabase = useCallback(async (userId: string, options: SyncOptions) => {
    if (!shouldSync(userId, options)) {
      return
    }

    return userCache.getSyncPromise(userId, async () => {
      try {
        const response = await fetch('/api/users/sync', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' }
        })

        if (!response.ok) {
          throw new Error(`Sync failed: ${response.status}`)
        }

        userCache.recordSync(userId)
        console.log(`User synced to database: ${userId} (trigger: ${options.trigger})`)
      } catch (error) {
        console.error('Failed to sync user to database:', error)
        throw error
      }
    })
  }, [])

  // 获取用户数据
  const fetchUserData = useCallback(async (userId: string, options: SyncOptions) => {
    // 先检查缓存
    if (!options.skipCache) {
      const cachedData = userCache.getUserData(userId)
      if (cachedData) {
        setState(prev => ({
          ...prev,
          userData: cachedData,
          isAdmin: cachedData.isAdmin || false,
        }))
        return cachedData
      }
    }

    try {
      const response = await fetch('/api/users/sync')
      if (!response.ok) {
        throw new Error(`Failed to fetch user data: ${response.status}`)
      }

      const data = await response.json()
      const userData = data.user as UserData

      // 更新缓存
      userCache.setUserData(userId, userData)

      // 更新状态
      setState(prev => ({
        ...prev,
        userData,
        isAdmin: userData.isAdmin || false,
      }))

      return userData
    } catch (error) {
      console.error('Failed to fetch user data:', error)
      throw error
    }
  }, [])

  // 处理用户状态变化
  const handleUserChange = useCallback(async (
    user: User | null, 
    trigger: SyncTrigger = SyncTrigger.INITIAL_LOAD
  ) => {
    // 更新用户状态
    setState(prev => ({
      ...prev,
      user,
      loading: false,
    }))

    // 如果用户变化了，清除旧用户的缓存
    if (currentUserIdRef.current && currentUserIdRef.current !== user?.id) {
      userCache.clearUserCache(currentUserIdRef.current)
    }
    currentUserIdRef.current = user?.id || null

    if (!user) {
      setState(prev => ({
        ...prev,
        userData: null,
        isAdmin: false,
      }))
      return
    }

    try {
      const syncOptions: SyncOptions = { trigger }

      // 并行执行同步和获取用户数据
      await Promise.all([
        syncUserToDatabase(user.id, syncOptions),
        fetchUserData(user.id, syncOptions),
      ])

      console.log(`User data loaded: ${user.id} (trigger: ${trigger})`)
    } catch (error) {
      console.error('Failed to handle user change:', error)
    }
  }, [syncUserToDatabase, fetchUserData])

  // 初始化和监听认证状态变化
  useEffect(() => {
    let mounted = true

    const initializeAuth = async () => {
      try {
        // 获取当前用户
        const { data: { user } } = await supabase.auth.getUser()
        
        if (mounted) {
          await handleUserChange(user, SyncTrigger.INITIAL_LOAD)
          isInitializedRef.current = true
        }
      } catch (error) {
        console.error('Failed to initialize auth:', error)
        if (mounted) {
          setState(prev => ({ ...prev, loading: false }))
        }
      }
    }

    initializeAuth()

    // 监听认证状态变化
    const { data: { subscription } } = supabase.auth.onAuthStateChange(async (event, session) => {
      if (!mounted || !isInitializedRef.current) return

      const user = session?.user ?? null
      
      // 根据事件类型确定同步触发器
      let trigger = SyncTrigger.INITIAL_LOAD
      if (event === 'SIGNED_IN') {
        trigger = SyncTrigger.SIGN_IN
      }

      await handleUserChange(user, trigger)
    })

    return () => {
      mounted = false
      subscription.unsubscribe()
    }
  }, [supabase.auth, handleUserChange])

  // 手动刷新用户数据
  const refreshUserData = useCallback(async (force = false) => {
    if (!state.user) return

    try {
      setState(prev => ({ ...prev, loading: true }))

      const syncOptions: SyncOptions = {
        trigger: SyncTrigger.MANUAL_REFRESH,
        force,
        skipCache: force,
      }

      await Promise.all([
        syncUserToDatabase(state.user.id, syncOptions),
        fetchUserData(state.user.id, syncOptions),
      ])
    } catch (error) {
      console.error('Failed to refresh user data:', error)
    } finally {
      setState(prev => ({ ...prev, loading: false }))
    }
  }, [state.user, syncUserToDatabase, fetchUserData])

  // 登出
  const signOut = useCallback(async () => {
    try {
      await supabase.auth.signOut()
      
      // 清除缓存
      if (currentUserIdRef.current) {
        userCache.clearUserCache(currentUserIdRef.current)
      }
      
      // 重定向到首页
      window.location.href = '/'
    } catch (error) {
      console.error('Failed to sign out:', error)
    }
  }, [supabase.auth])

  // 触发用户信息更新（用于个人资料更新后）
  const triggerProfileUpdate = useCallback(async () => {
    if (!state.user) return

    const syncOptions: SyncOptions = {
      trigger: SyncTrigger.PROFILE_UPDATE,
      force: true,
      skipCache: true,
    }

    try {
      await Promise.all([
        syncUserToDatabase(state.user.id, syncOptions),
        fetchUserData(state.user.id, syncOptions),
      ])
    } catch (error) {
      console.error('Failed to update profile:', error)
    }
  }, [state.user, syncUserToDatabase, fetchUserData])

  // 触发订阅状态更新
  const triggerSubscriptionUpdate = useCallback(async () => {
    if (!state.user) return

    const syncOptions: SyncOptions = {
      trigger: SyncTrigger.SUBSCRIPTION_CHANGE,
      force: true,
      skipCache: true,
    }

    try {
      await fetchUserData(state.user.id, syncOptions)
    } catch (error) {
      console.error('Failed to update subscription:', error)
    }
  }, [state.user, fetchUserData])

  return {
    user: state.user,
    userData: state.userData,
    loading: state.loading,
    isAdmin: state.isAdmin,
    signOut,
    refreshUserData,
    triggerProfileUpdate,
    triggerSubscriptionUpdate,
  }
}
