'use client'

import { useEffect, useState } from 'react'
import { useAuth } from './useAuth'

interface UserData {
  id: string
  email: string
  username: string | null
  avatar: string | null
  bio: string | null
  language: string
  isAdmin: boolean
  versionLimit: number
  subscribePlan: string
  maxVersionLimit: number
  promptLimit: number
  creditBalance: number
  createdAt: Date
  updatedAt: Date
}

export function useUser() {
  const { user: supabaseUser, loading: authLoading } = useAuth()
  const [userData, setUserData] = useState<UserData | null>(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    const fetchUserData = async () => {
      if (!supabaseUser) {
        setUserData(null)
        setLoading(false)
        return
      }

      try {
        const response = await fetch('/api/users/sync')
        if (response.ok) {
          const data = await response.json()
          setUserData(data.user)
        }
      } catch (error) {
        console.error('Failed to fetch user data:', error)
      } finally {
        setLoading(false)
      }
    }

    if (!authLoading) {
      fetchUserData()
    }
  }, [supabaseUser, authLoading])

  return {
    user: supabaseUser,
    userData,
    loading: authLoading || loading,
    isAdmin: userData?.isAdmin || false
  }
}