import { AxiosError } from 'axios'
import { useEffect, useState } from 'react'
import { toast } from 'react-toastify'
import axios from '../config/axios'
import { isDevelopment } from '../constants'
import { urlTenantKey } from '../contexts/Providers'
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',
}
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) {
  const insititutionKey = getInstitutionKey()
  if (institutions?.length === 0) {
    openRootModal({
      key: 'institutions-not-assigned',
      dialogProps: {
        disableEscapeKeyDown: true,
        onClose: () => {},
      },
    })
  }
  if (institutions?.length === 1) {
    if (!insititutionKey) {
      window.location.replace(
        `${window.location.origin}/${urlTenantKey}/${institutions[0]?.code}`,
      )
    }
    if (insititutionKey !== institutions[0]?.code) {
      window.location.replace(
        `${window.location.origin}/${urlTenantKey}/${institutions[0]?.code}`,
      )
    }
    InstitutionsStore.update((s) => {
      s.current = institutions[0]
      s.institutions = institutions
    })
  }
  if (institutions?.length > 1) {
    if (!insititutionKey) {
      openRootModal({
        key: 'institutions',
        dialogProps: {
          disableEscapeKeyDown: true,
          onClose: () => {},
          maxWidth: 'md',
        },
      })
    }
    if (
      insititutionKey &&
      !institutions?.find((item) => item.code === insititutionKey)
    ) {
      openRootModal({
        key: 'institutions',
        dialogProps: {
          disableEscapeKeyDown: true,
          onClose: () => {},
        },
      })
    }
    InstitutionsStore.update((s) => {
      s.institutions = institutions
      s.current = institutions.find((item) => item.code === insititutionKey)
    })
  }
}

const loginErrorHandler = ({
  loginUrl,
  setLoading,
  err,
}: {
  loginUrl: string
  setLoading?: any
  err: AxiosError
}) => {
  setLoading && setLoading(false)
  const origin = window.location.origin
  const isStaging = origin.split('campx')[1] === '.dev'
  const isSetup = window.location.hostname.split('.').includes('setup')

  if (isDevelopment || isStaging || isSetup) {
    openRootModal({
      key: 'login',
      contentData: {
        loginUrl,
      },
      dialogProps: {
        disableEscapeKeyDown: true,
        onClose: () => {},
      },
    })
    return
  } else {
    window.location.replace(`https://www.id.campx.in/?redirect_to=${url}`)
  }

  if (err.response.status !== 401) {
    if (err.response.status > 400 && err.response.status < 500) {
      window.location.replace(`https://www.id.campx.in/?redirect_to=${url}`)
    } else {
      toast.error('Server Error')
    }
  }
}

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

  const appInit = async () => {
    setLoading(true)
    axios
      .get(permissionsEndpoint)
      .then((res) => {
        const origin = window.location.origin
        const originSubdomain =
          window.location.host.split('.')?.slice(-3)[0] ?? 'ums'
        const isStaging = origin.split('campx')[1] === '.dev'
        const isAdmin = checkIsAdmin(res.data.user)
        const isSetup =
          window.location.hostname.split('.').includes('setup') && isAdmin
        const isMasterSlave = res.data?.institutionType === 'MASTER_CHILD'

        // eslint-disable-next-line no-console

        if (isDevelopment == false && isStaging == false && !isSetup) {
          if (
            !res.data.applications.includes(ApplicationObj[originSubdomain])
          ) {
            window.location.replace(
              `https://www.id.campx.in/apps?redirect_to=${url}`,
            )
          }
        }

        if (res.data?.institutions) {
          handleInstitutions(res.data?.institutions)
        }

        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,
          } as any
          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
        })
        AssetsStore.update((s) => {
          s.logo = res.data?.assets.logo
          s.logo_square = res.data?.assets.logo_square
        })

        setLoading(false)
      })
      .catch((err: AxiosError) => {
        loginErrorHandler({ loginUrl, setLoading, err })
      })
  }

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

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

export default useAuth
