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

export function RoleSelectPage() {
  const { user, roles, selectedRole, setSelectedRole } = useAuth()
  const navigate = useNavigate()
  const location = useLocation()
  const [busyRole, setBusyRole] = useState<string | null>(null)
  const [busy, setBusy] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const from = (location.state as { from?: string } | null)?.from ?? '/app/home'

  async function continueLogin(nextRole: string) {
    setBusy(true)
    setBusyRole(nextRole)
    setError(null)
    setSelectedRole(nextRole)

    let target = from.startsWith('/app') ? from : '/app/home'
    if (nextRole.toLowerCase() === 'parent' && target === '/app/home') {
      target = '/app/parent/home'
    }
    try {
      const dash = await fetchDashboardRoute()
      const route = dash.data?.dashboard?.route
      const mapped = spaPathFromCiUrl(route)
      if (mapped) target = mapped
    } catch {
      /* keep fallback target */
    }

    navigate(target, { replace: true })
  }

  return (
    <div className="container mt-5">
      <div className="card shadow-sm border-0 mx-auto" style={{ maxWidth: 720 }}>
        <div className="card-header bg-primary text-white">
          <h4 className="mb-0">Select Account Type</h4>
        </div>
        <div className="card-body">
          <p className="mb-4">
            {user?.name ? `${user.name}, y` : 'Y'}ou have multiple roles. Please select the account
            you&apos;d like to log into:
          </p>

          <div className="d-flex flex-wrap gap-3">
            {roles.map((role) => (
              <button
                key={role}
                type="button"
                className={`btn ${
                  selectedRole === role ? 'btn-primary' : 'btn-outline-primary'
                }`}
                onClick={() => {
                  void continueLogin(role)
                }}
                disabled={busy}
              >
                {busy && busyRole === role
                  ? 'Opening...'
                  : role.replace(/_/g, ' ').replace(/\b\w/g, (letter) => letter.toUpperCase())}
              </button>
            ))}
          </div>

          {error ? (
            <div className="alert alert-danger py-2 mt-3" role="alert">
              {error}
            </div>
          ) : null}

        </div>
      </div>
    </div>
  )
}
