import { createContext, useContext, useState, useCallback, useEffect, type ReactNode } from 'react'
import { api, endpoints, setToken } from '../api'
import type { AuthUser } from '../types'

interface AuthState {
  user: AuthUser | null
  loading: boolean
  login: (email: string, password: string) => Promise<void>
  logout: () => Promise<void>
  hasPermission: (perm: string) => boolean
}

const AuthContext = createContext<AuthState>(null!)

export function useAuth() {
  return useContext(AuthContext)
}

export function AuthProvider({ children }: { children: ReactNode }) {
  const [user, setUser] = useState<AuthUser | null>(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    api.get<{ user: AuthUser; token: string }>(endpoints.admin.authRefresh())
      .then(data => {
        setToken(data.token)
        setUser(data.user)
      })
      .catch(() => {})
      .finally(() => setLoading(false))
  }, [])

  const login = useCallback(async (email: string, password: string) => {
    const data = await api.post<{ token: string; user: AuthUser }>(endpoints.admin.authLogin(), { email, password })
    setToken(data.token)
    setUser(data.user)
  }, [])

  const logout = useCallback(async () => {
    try { await api.post(endpoints.admin.authLogout()) } catch {}
    setToken(null)
    setUser(null)
  }, [])

  const hasPermission = useCallback((perm: string) => {
    return user?.permissions.includes(perm) ?? false
  }, [user])

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