'use client'

import { getGitHubToken } from '@/actions/github'
import { useAuth } from '@clerk/nextjs'
import { useEffect, useState } from 'react'

interface UseGitHubTokenReturn {
  token: string | null
  isLoading: boolean
  error: string | null
  refreshToken: () => Promise<void>
}

/**
 * A hook to get the current user's GitHub OAuth token from Clerk
 * This ensures each user gets their own token for GitHub API calls
 */
export function useGitHubToken(): UseGitHubTokenReturn {
  const [token, setToken] = useState<string | null>(null)
  const [isLoading, setIsLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  const { isLoaded: isAuthLoaded, userId } = useAuth()

  const fetchToken = async () => {
    if (!userId) {
      setError('User not authenticated')
      setIsLoading(false)
      return
    }

    try {
      setIsLoading(true)
      setError(null)

      const userToken = await getGitHubToken()

      if (!userToken) {
        setError(
          'GitHub account not connected. Please connect your GitHub account.'
        )
        setToken(null)
      } else {
        console.log('✅ Successfully retrieved user-specific GitHub token')
        setToken(userToken)
      }
    } catch (err) {
      console.error('❌ Error getting GitHub token:', err)
      setError(
        err instanceof Error ? err.message : 'Failed to get GitHub token'
      )
      setToken(null)
    } finally {
      setIsLoading(false)
    }
  }

  useEffect(() => {
    if (isAuthLoaded) {
      fetchToken()
    }
  }, [isAuthLoaded, userId])

  const refreshToken = async () => {
    await fetchToken()
  }

  return { token, isLoading, error, refreshToken }
}
