import { useState } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'
import { fetchDashboardRoute, postRoleSwitch } from '../api/session'
import { useAuth } from '../auth/AuthProvider'
import { spaPathFromCiUrl } from '../lib/ciSpaPaths'
import { isParentPortalRole, isTeacherPortalRole } from '../lib/portalRoles'

/** Shared navigation after JWT login when the account has multiple roles (CI `welcome_back` / `select_role`). */
export function useContinueWithRole() {
  const { setSelectedRole } = useAuth()
  const navigate = useNavigate()
  const location = useLocation()
  const [busy, setBusy] = useState(false)
  const [busyRole, setBusyRole] = useState<string | null>(null)
  const [error, setError] = useState<string | null>(null)
  const from = (location.state as { from?: string } | null)?.from ?? '/app/home'

  async function continueWithRole(nextRole: string) {
    setBusy(true)
    setBusyRole(nextRole)
    setError(null)
    try {
      const fromApp = from.startsWith('/app') ? from : ''
      const hasDeepLink = Boolean(fromApp && fromApp !== '/app/home')

      let target: string | null = null
      try {
        const switched = await postRoleSwitch(nextRole)
        const route = switched.data?.dashboard_route
        const mapped = route ? spaPathFromCiUrl(route) : null
        if (mapped) {
          target = mapped
        }
      } catch {
        /* fall back to client-side role defaults */
      }

      setSelectedRole(nextRole)

      if (hasDeepLink) {
        target = fromApp
      } else if (isParentPortalRole(nextRole)) {
        target = '/app/parent/home'
      } else if (isTeacherPortalRole(nextRole)) {
        target = '/app/teacher_dashboard'
      } else if (!target) {
        target = '/app/home'
        try {
          const dash = await fetchDashboardRoute()
          const route = dash.data?.dashboard?.route
          const mapped = spaPathFromCiUrl(route)
          if (mapped) target = mapped
        } catch {
          /* keep default */
        }
      }

      navigate(target ?? '/app/home', { replace: true })
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Unable to continue.')
    } finally {
      setBusy(false)
      setBusyRole(null)
    }
  }

  return { continueWithRole, busy, busyRole, error, setError, from }
}
