"use client"

import { createContext, useState, useEffect, useCallback, type ReactNode } from "react"
import api from "@/lib/api"
import { getTokens, setTokens, clearTokens } from "@/lib/auth"
import type { AuthResponse, UserResponse } from "@/lib/types"

interface AuthContextValue {
  user: UserResponse | null
  isAuthenticated: boolean
  isAdmin: boolean
  isLoading: boolean
  login: (email: string, password: string) => Promise<void>
  register: (username: string, email: string, password: string) => Promise<void>
  logout: () => void
}

export const AuthContext = createContext<AuthContextValue | null>(null)

export function AuthProvider({ children }: { children: ReactNode }) {
  const [user, setUser] = useState<UserResponse | null>(null)
  const [isLoading, setIsLoading] = useState(true)

  useEffect(() => {
    const { access } = getTokens()
    if (!access) {
      setIsLoading(false)
      return
    }
    api
      .get<UserResponse>("/auth/me")
      .then((res) => setUser(res.data))
      .catch(() => clearTokens())
      .finally(() => setIsLoading(false))
  }, [])

  const login = useCallback(async (email: string, password: string) => {
    const { data } = await api.post<AuthResponse>("/auth/login", {
      email,
      password,
    })
    setTokens(data.token, data.refresh_token)
    setUser(data.user)
  }, [])

  const register = useCallback(
    async (username: string, email: string, password: string) => {
      const { data } = await api.post<AuthResponse>("/auth/register", {
        username,
        email,
        password,
      })
      setTokens(data.token, data.refresh_token)
      setUser(data.user)
    },
    [],
  )

  const logout = useCallback(() => {
    api.post("/auth/logout").catch(() => {})
    clearTokens()
    setUser(null)
    window.location.href = "/login"
  }, [])

  return (
    <AuthContext.Provider
      value={{
        user,
        isAuthenticated: !!user,
        isAdmin: user?.role === "admin",
        isLoading,
        login,
        register,
        logout,
      }}
    >
      {children}
    </AuthContext.Provider>
  )
}
