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 [pickedRole, setPickedRole] = useState<string | null>(selectedRole)
  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() {
    if (!pickedRole) {
      setError('Please select a role to continue.')
      return
    }
    setBusy(true)
    setError(null)
    setSelectedRole(pickedRole)

    let target = from.startsWith('/app') ? from : '/app/home'
    if (pickedRole.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 py-4">
      <div className="card border-0 shadow-sm mx-auto" style={{ maxWidth: 640 }}>
        <div className="card-body p-4">
          <h2 className="h4 mb-2">Select role</h2>
          <p className="text-muted mb-3">
            {user?.name ? `Signed in as ${user.name}.` : 'Signed in successfully.'} Choose a role
            to continue.
          </p>

          <div className="list-group mb-3">
            {roles.map((role) => (
              <button
                key={role}
                type="button"
                className={`list-group-item list-group-item-action text-start ${
                  pickedRole === role ? 'active' : ''
                }`}
                onClick={() => setPickedRole(role)}
              >
                {role}
              </button>
            ))}
          </div>

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

          <div className="d-grid">
            <button type="button" className="btn btn-success" onClick={continueLogin} disabled={busy}>
              {busy ? 'Continuing…' : 'Continue'}
            </button>
          </div>
        </div>
      </div>
    </div>
  )
}
