import React from 'react'
import { UserStore } from '../shared-state'
import {
  EnrollPermissions,
  PaymentsPermission,
  Permission,
  PermissionsStore,
  SquarePermissions,
} from '../shared-state/PermissionsStore'

export default function ValidateAccess({
  accessKey,
  children,
  checkForMasterSlave = false,
  checkIsMasterInstitution = false,
}: {
  accessKey:
    | Permission
    | SquarePermissions
    | EnrollPermissions
    | PaymentsPermission
  children: React.ReactNode
  checkForMasterSlave?: boolean
  checkIsMasterInstitution?: boolean
}) {
  const {
    permissions,
    institutionType,
    masterInstitutionUniqueId,
    isMasterInstitution,
  } = PermissionsStore.useState((s) => s)

  const { user } = UserStore.useState((s) => s)
  const hasAccess = checkHasAccess(
    checkForMasterSlave,
    accessKey,
    institutionType,
    permissions,
    checkIsMasterInstitution,
    isMasterInstitution,
    masterInstitutionUniqueId,
    user,
  )

  if (hasAccess) {
    return <>{children}</>
  }
  return null
}

const checkHasAccess = (
  checkForMasterSlave,
  accessKey,
  institutionType,
  permissions,
  checkIsMasterInstitution,
  isMasterInstitution,
  masterInstitutionUniqueId,
  user,
) => {
  if (checkForMasterSlave) {
    if (institutionType == 'MASTER_CHILD') {
      if (checkIsMasterInstitution) {
        return (
          permissions[accessKey] &&
          user.institutionIds.includes(masterInstitutionUniqueId) &&
          isMasterInstitution
        )
      }
      return accessKey ? permissions[accessKey] : true
    }
  }
  return accessKey ? permissions[accessKey] : true
}
