import { useState, useEffect, useCallback } from 'react'
import { useAuth } from '../contexts/AuthContext'

export const usePermissions = () => {
  const { authFetch, isAuthenticated } = useAuth()
  const [permissions, setPermissions] = useState({
    hasFullAccess: false,
    accessibleSpaces: [],
    canCreateSpace: false,
    canDeleteSpace: false,
    canCreateFqdn: {},
    canDeleteFqdn: {},
    canUploadCSR: {},
    canSignCSR: {},
  })
  const [loading, setLoading] = useState(true)

  const fetchPermissions = useCallback(async () => {
    if (!isAuthenticated) {
      setLoading(false)
      return
    }

    try {
      setLoading(true)
      const response = await authFetch('/api/user/permissions')
      if (response.ok) {
        const data = await response.json()
        setPermissions({
          hasFullAccess: data.hasFullAccess || false,
          accessibleSpaces: data.accessibleSpaces || [],
          canCreateSpace: data.permissions?.canCreateSpace || false,
          canDeleteSpace: data.permissions?.canDeleteSpace || false,
          canCreateFqdn: data.permissions?.canCreateFqdn || {},
          canDeleteFqdn: data.permissions?.canDeleteFqdn || {},
          canUploadCSR: data.permissions?.canUploadCSR || {},
          canSignCSR: data.permissions?.canSignCSR || {},
        })
      }
    } catch (err) {
      console.error('Error fetching permissions:', err)
    } finally {
      setLoading(false)
    }
  }, [isAuthenticated, authFetch])

  useEffect(() => {
    if (isAuthenticated) {
      fetchPermissions()
    } else {
      setPermissions({
        hasFullAccess: false,
        accessibleSpaces: [],
        canCreateSpace: false,
        canDeleteSpace: false,
        canCreateFqdn: {},
        canDeleteFqdn: {},
        canUploadCSR: {},
        canSignCSR: {},
      })
      setLoading(false)
    }
  }, [isAuthenticated, fetchPermissions])

  const canCreateSpace = () => permissions.canCreateSpace
  const canDeleteSpace = (spaceId) => permissions.canDeleteSpace
  const canCreateFqdn = (spaceId) => permissions.canCreateFqdn[spaceId] === true
  const canDeleteFqdn = (spaceId) => permissions.canDeleteFqdn[spaceId] === true
  const canUploadCSR = (spaceId) => permissions.canUploadCSR[spaceId] === true
  const canSignCSR = (spaceId) => permissions.canSignCSR[spaceId] === true
  const hasAccessToSpace = (spaceId) => permissions.accessibleSpaces.includes(spaceId)

  return {
    permissions,
    loading,
    refreshPermissions: fetchPermissions,
    canCreateSpace,
    canDeleteSpace,
    canCreateFqdn,
    canDeleteFqdn,
    canUploadCSR,
    canSignCSR,
    hasAccessToSpace,
  }
}

