import { createContext, useContext, useState } from "react"
import instance from "../api/axiosInstance"

type AuthContextType = {
  user: any
  token: string | null
  isAuthenticated: boolean
  login: (userData: any, tokenData: string) => void
  logout: () => Promise<void>
}

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

export function AuthProvider({ children }: { children: React.ReactNode }) {
  const [token, setToken] = useState<string | null>(() => localStorage.getItem("token"))
  const [user, setUser] = useState<any>(() => {
    const raw = localStorage.getItem("user")
    return raw ? JSON.parse(raw) : null
  })

  const login = (userData: any, tokenData: string) => {
    localStorage.setItem("user", JSON.stringify(userData))
    localStorage.setItem("token", tokenData)
    setUser(userData)
    setToken(tokenData)
  }

  const logout = async () => {
    try {
      await instance.post("/auth/logout")
    } catch {}
    localStorage.removeItem("user")
    localStorage.removeItem("token")
    setUser(null)
    setToken(null)
  }

  return (
    <AuthContext.Provider
      value={{
        user,
        token,
        isAuthenticated: Boolean(token),
        login,
        logout,
      }}
    >
      {children}
    </AuthContext.Provider>
  )
}

export function useAuth() {
  const ctx = useContext(AuthContext)
  if (!ctx) throw new Error("useAuth must be used within AuthProvider")
  return ctx
}
