"use client"
import React, { createContext, useContext, useEffect, useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { fetchUserProfile, profileQueryKey } from '@/lib/react-query/queries/auth'
import Cookies from 'js-cookie'
import { useRouter } from 'next/navigation'
import { useLocale } from 'next-intl'
import type { User } from '@/types/auth'
import { queryClient } from '@/lib/react-query/client'

interface AuthContextType {
  user: User | null
  isLoading: boolean
  isAuthenticated: boolean
  refetchProfile: () => void
  logout: () => void
  updateUser: (user: User | null) => void
  updateToken: (token: string | null) => void
}

const AuthContext = createContext<AuthContextType | undefined>(undefined)

export function AuthProvider({ children }: { children: React.ReactNode }) {
  const [isAuthenticated, setIsAuthenticated] = useState(false)
  const [user, setUser] = useState<User | null>(null)
  const [tokenChecked, setTokenChecked] = useState(false)
  const [token, setToken] = useState<string | null>(null)
  const locale = useLocale()
  const router = useRouter()

  // Check for token on mount
  useEffect(() => {
    const existingToken = Cookies.get('iit_token')
    setToken(existingToken || null)
    setIsAuthenticated(!!existingToken)
    setTokenChecked(true)
  }, [])

  // Update token state when it changes (for login/logout)
  const updateToken = (newToken: string | null) => {
    setToken(newToken)
    setIsAuthenticated(!!newToken)
  }

  // Only fetch profile if we have a token
  const {
    data: profileData,
    isLoading,
    refetch: refetchProfile
  } = useQuery({
    queryKey: profileQueryKey,
    queryFn: fetchUserProfile,
    enabled: !!token,
    retry: 2
  })

  // Update user state when profile data changes
  useEffect(() => {
    if (profileData && isAuthenticated) {
      setUser(profileData)
    } else if (!isAuthenticated) {
      setUser(null)
    }
  }, [profileData, isAuthenticated])

  // Refetch profile when token changes
  useEffect(() => {
    if (token) {
      refetchProfile()
    }
  }, [token, refetchProfile])

  // Logout function
  const logout = () => {
    // Remove token from cookies
    Cookies.remove('iit_token')
    // Update token state
    updateToken(null)
    setUser(null)
    queryClient.clear()
    // Redirect to login page
    router.push(`/${locale}/sign-in`)
  }

  // Function to manually update user data
  const updateUser = (userData: User | null) => {
    setUser(userData)
  }

  // Don't render children until we've checked for token
  if (!tokenChecked) {
    return null // or a loading spinner
  }

  const value: AuthContextType = {
    user,
    isLoading: isAuthenticated ? isLoading : false,
    isAuthenticated,
    refetchProfile,
    logout,
    updateUser,
    updateToken
  }

  return (
    <AuthContext.Provider value={value}>
      {children}
    </AuthContext.Provider>
  )
}

export function useAuth() {
  const context = useContext(AuthContext)
  if (context === undefined) {
    throw new Error('useAuth must be used within an AuthProvider')
  }
  return context
}