"use client"

import React, { createContext, useContext, useState, useEffect } from "react"
import { getApiUrl } from "@/lib/api-config"

interface User {
    id: number
    email: string
    is_active: boolean
    is_superuser: boolean
    role: string
}

interface AuthContextType {
    user: User | null
    token: string | null
    loading: boolean
    login: (token: string) => Promise<void>
    logout: () => void
}

const AuthContext = createContext<AuthContextType>({
    user: null,
    token: null,
    loading: true,
    login: async () => { },
    logout: () => { },
})

export function AuthProvider({ children }: { children: React.ReactNode }) {
    const [user, setUser] = useState<User | null>(null)
    const [token, setToken] = useState<string | null>(null)
    const [loading, setLoading] = useState(true)

    useEffect(() => {
        const initAuth = async () => {
            const storedToken = localStorage.getItem("token")
            if (storedToken) {
                setToken(storedToken)
                try {
                    await fetchUser(storedToken)
                } catch (err) {
                    console.error("Auth init failed", err)
                    localStorage.removeItem("token")
                    setToken(null)
                }
            }
            setLoading(false)
        }
        initAuth()
    }, [])

    const fetchUser = async (token: string) => {
        const res = await fetch(`${getApiUrl()}/auth/users/me`, {
            headers: {
                Authorization: `Bearer ${token}`
            }
        })
        if (res.ok) {
            const userData = await res.json()
            setUser(userData)
        } else {
            throw new Error("Failed to fetch user")
        }
    }

    const login = async (newToken: string) => {
        localStorage.setItem("token", newToken)
        setToken(newToken)
        await fetchUser(newToken)
    }

    const logout = () => {
        localStorage.removeItem("token")
        setToken(null)
        setUser(null)
    }

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

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