'use client'

import { createContext, useContext, useEffect, useState } from 'react'
import Loading from '../components/layout/shared/Loading'
import { User } from '../types/services/user'

type AuthContextType = {
  isAuthenticated: boolean
  token: string | null
  currentUser: User | null
}

const AuthContext = createContext<AuthContextType>({
  isAuthenticated: false,
  token: null,
  currentUser: null
})

export const AuthProvider = ({ children }: { children: React.ReactNode }) => {
  const [token, setToken] = useState<string | null>(null)
  const [currentUser, setCurrentUser] = useState<User | null>(null)
  const [isInitialized, setIsInitialized] = useState(false)

  useEffect(() => {
    const savedToken = localStorage.getItem('authToken')
    const savedUser = localStorage.getItem('user')
    if (savedToken) setToken(savedToken)
    if (savedUser) setCurrentUser(JSON.parse(savedUser))
    setIsInitialized(true)
  }, [])

  if (!isInitialized) return <Loading />

  return (
    <AuthContext.Provider
      value={{
        isAuthenticated: !!token,
        token,
        currentUser
      }}
    >
      {children}
    </AuthContext.Provider>
  )
}

export const useAuth = () => useContext(AuthContext)
