import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { toast } from 'react-toastify'
import axios from '../config/axios'
import { isDevelopment } from '../constants'
import { openRootModal } from '../contexts/RootModal'
import { AssetsStore, PermissionsStore, UserStore } from '../shared-state'
import { InstitutionsStore } from '../shared-state/InstitutionsStore'

const url = window.location.origin

type AuthParams = {
  permissionsEndpoint: string
  loginUrl?: string
}

type AuthResponse = {
  loading: boolean
  data: {
    user?: any
    roles?: any
    fullName?: any
    permissions?: any
    assets?: {
      logo: string
      logo_square: string
    }
    isHomePageEnabled?: boolean
  }
}

const ApplicationObj = {
  admin: 'admin',
  enroll: 'enroll_x',
  ums: 'square',
  payments: 'payments',
  exams: 'exams',
  hostel: 'hostels',
  people: 'hrms',
  commute: 'commute_x',
}
export const checkIsAdmin = (user) => {
  let subDomain = window.location.host.split('.')?.slice(-3)[0]
  const localSubDomain = process.env.REACT_APP_SUBDOMAIN

  if (user?.isSuperUser) return 1

  if (process.env.NODE_ENV === 'development') {
    subDomain = localSubDomain

    if (!localSubDomain) {
      toast.warn('missing REACT_APP_SUBDOMAIN in .env')
    }
  }

  const profiles: any[] = user?.profiles?.filter(
    (item) => item.application == ApplicationObj[subDomain],
  )

  const isAdmin = profiles.some((profile) => {
    profile.isAdmin
  })
  return isAdmin ? 1 : 0
}
const getInstitutionKey = () => {
  const instituitionKey = window.location.pathname.split('/')[2]
  if (!instituitionKey) {
    const localInstituitionKey = localStorage.getItem('institution_key')
    if (localInstituitionKey) {
      return localInstituitionKey
    } else {
      return null
    }
  } else {
    return instituitionKey
  }
}

function handleInstitutions(institutions) {
  if (institutions?.length === 0) {
    openRootModal({
      key: 'institutions-not-assigned',
      dialogProps: {
        disableEscapeKeyDown: true,
        onClose: () => {},
      },
    })
  } else {
    InstitutionsStore.update((s) => {
      s.current = institutions[0]
      s.institutions = institutions
    })
  }
}

const useAuth = ({
  permissionsEndpoint,
  loginUrl,
}: AuthParams): AuthResponse => {
  const [loading, setLoading] = useState<boolean>(true)
  const [data, setData] = useState<any>(null)
  const { current } = InstitutionsStore.useState()
  const navigate = useNavigate()

  const appInit = async () => {
    try {
      const res = await axios.get(permissionsEndpoint)
      const isAdmin = checkIsAdmin(res.data.user)
      setLoading(false)
      setData(res.data)

      UserStore.update((s) => {
        s.username = res.data?.user?.username
        s.user = res.data?.user
        s.roles = res.data?.roles
        s.globalUserId = res.data?.globalUserId
        s.fullName = res.data?.fullName
      })

      PermissionsStore.update((s) => {
        s.permissions = {
          ...res.data?.permissions,
          can_settings_view: 1,
          can_dashboard_view: 1,
          can_individual_pages_view: 1,
          can_analatics_view: isAdmin,
          can_admin_view: isAdmin,
          can_my_mentees_view:
            res.data?.user?.isMentor &&
            res.data?.permissions.can_my_mentees_view,
        }
        s.applications = res.data?.applications ?? []
        s.institutionType = res.data?.institutionType
        s.masterInstitutionUniqueId = res.data?.masterInstitutionUniqueId
        s.masterInstitutionId = res.data?.masterInstitutionId
        s.isMasterInstitutionUser = res.data?.institutions
          ?.map((institution) => institution?.id)
          ?.includes(res?.data?.masterInstitutionUniqueId)
        s.isMasterInstitution = res.data?.isMasterInstitution
        s.isHomePageEnabled = res.data?.isHomePageEnabled
      })

      InstitutionsStore.update((s) => {
        s.institutions = res.data?.institutions
        s.current = res.data?.institutions.find(
          (institution) =>
            institution.code === window.location.pathname.split('/')[1],
        )
      })

      AssetsStore.update((s) => {
        s.logo = res.data?.assets.logo
        s.logo_square = res.data?.assets.logo_square
      })
    } catch (err: any) {
      setLoading(false)
      const origin = window.location.origin
      const isStaging = origin.split('campx')[1] === '.dev'

      if (isDevelopment || isStaging) {
        openRootModal({
          key: 'login',
          contentData: {
            loginUrl,
          },
          dialogProps: {
            disableEscapeKeyDown: true,
            onClose: () => {},
          },
        })
        return
      } else {
        navigate('/auth/login')
      }
    }
  }

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

  return {
    loading: loading || !data?.permissions || !current,
    data,
  }
}

export default useAuth
