import { createContext, useContext, useEffect, useState, ReactNode } from 'react'
import { apiClient } from '../api/client'
import { setVendorSlug } from '../utils/vendor'

interface Role {
  id: number
  name: string
  label?: string
}

interface VendorInfo {
  id: number
  name: string
  slug: string
}

interface User {
  id: number
  name: string
  username: string
  email?: string
  roles: Role[]
  permissions: string[]
  vendor?: VendorInfo
}

interface AuthContextType {
  user: User | null
  loading: boolean
  isAdmin: boolean
  hasRole: (roleName: string) => boolean
  hasPermission: (permission: string) => boolean
  canAccess: (permission: string) => boolean
  refreshUser: () => Promise<void>
}

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

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

  const loadUser = async () => {
    const token = localStorage.getItem('auth_token')
    if (!token) {
      setUser(null)
      setLoading(false)
      return
    }

    try {
      const res = await apiClient.get('/auth/user')
      const userData = res.data?.data ?? res.data?.user ?? res.data ?? null
      setUser(userData)
      if (userData?.vendor?.slug) {
        setVendorSlug(userData.vendor.slug)
      }
    } catch (err) {
      console.error('Failed to load user:', err)
      setUser(null)
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    loadUser()
  }, [])

  const hasRole = (roleName: string): boolean => {
    if (!user || !user.roles) return false
    return user.roles.some((r) => r.name === roleName)
  }

  const hasPermission = (permission: string): boolean => {
    if (!user || !user.permissions) return false
    return user.permissions.includes(permission)
  }

  const isAdmin = hasRole('admin')

  // Check if user can access a feature (admin always can, others need permission)
  const canAccess = (permission: string): boolean => {
    return isAdmin || hasPermission(permission)
  }

  return (
    <AuthContext.Provider
      value={{
        user,
        loading,
        isAdmin,
        hasRole,
        hasPermission,
        canAccess,
        refreshUser: loadUser,
      }}
    >
      {children}
    </AuthContext.Provider>
  )
}

export const useAuth = (): AuthContextType => {
  const context = useContext(AuthContext)
  if (!context) {
    throw new Error('useAuth must be used within an AuthProvider')
  }
  return context
}
