'use client'

import { createClient } from '@/lib/supabase'
import { User } from '@supabase/supabase-js'
import { useEffect, useState, useRef } from 'react'

export function useAuth() {
  const [user, setUser] = useState<User | null>(null)
  const [loading, setLoading] = useState(true)
  const supabase = createClient()
  const syncTimeoutRef = useRef<NodeJS.Timeout | null>(null)
  const lastSyncTimeRef = useRef<number>(0)
  const lastUserIdRef = useRef<string | null>(null)

  useEffect(() => {
    // 同步用户到Prisma数据库 - 带防抖和缓存
    const syncUser = async (userId: string) => {
      const now = Date.now()
      const timeSinceLastSync = now - lastSyncTimeRef.current
      
      // 如果是同一个用户且距离上次同步不到30秒，则跳过
      if (lastUserIdRef.current === userId && timeSinceLastSync < 30000) {
        return
      }

      // 清除之前的定时器
      if (syncTimeoutRef.current) {
        clearTimeout(syncTimeoutRef.current)
      }

      // 防抖处理：延迟500ms执行，避免频繁调用
      syncTimeoutRef.current = setTimeout(async () => {
        try {
          await fetch('/api/users/sync', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' }
          })
          lastSyncTimeRef.current = Date.now()
          lastUserIdRef.current = userId
        } catch (error) {
          console.error('Failed to sync user:', error)
        }
      }, 500)
    }

    const getUser = async () => {
      const { data: { user: userData } } = await supabase.auth.getUser()
      if (userData) {
        await syncUser(userData.id)
      }
      setUser(userData)
      setLoading(false)
    }

    getUser()

    const { data: { subscription } } = supabase.auth.onAuthStateChange(async (event, session) => {
      const userData = session?.user ?? null
      
      // 只在首次登录时同步，不在token刷新时同步
      if (userData && event === 'SIGNED_IN') {
        await syncUser(userData.id)
      }
      
      setUser(userData)
      setLoading(false)
    })

    return () => {
      subscription.unsubscribe()
      if (syncTimeoutRef.current) {
        clearTimeout(syncTimeoutRef.current)
      }
    }
  }, [supabase.auth])

  const signOut = async () => {
    await supabase.auth.signOut()
    window.location.href = '/'
  }

  return {
    user,
    loading,
    signOut
  }
}