import { Link } from 'react-router-dom'
import { useAuth } from '../auth/AuthProvider'
import { useContinueWithRole } from '../hooks/useContinueWithRole'

export function RoleSelectPage() {
  const { user, roles } = useAuth()
  const { continueWithRole, busy, busyRole, error } = useContinueWithRole()

  return (
    <div className="registration-form container mt-5 mb-5">
      <div className="row justify-content-center">
        <div className="text-center mb-4">
          <Link to="/">
            <img
              src="/images/alrahma_logo.png"
              alt="Al Rahma Sunday School"
              style={{ width: 180, height: 120, objectFit: 'contain' }}
            />
          </Link>
        </div>

        <h3 className="text-center text-success" style={{ fontFamily: 'Arial, sans-serif' }}>
          Select Your Role to Log In
        </h3>

        <p className="text-center text-muted mt-2">
          {user?.name ? `${user.name}, you` : 'You'} have multiple roles. Choose how you want to
          continue.
        </p>

        <div className="d-flex flex-wrap justify-content-center gap-3 mt-4">
          {roles.map((role) => {
            const label = role.replace(/_/g, ' ').replace(/\b\w/g, (letter) => letter.toUpperCase())
            return (
              <div key={role} className="mb-3 d-grid">
                <button
                  type="button"
                  className="btn btn-lg btn-success"
                  title={`Log in as ${label}`}
                  onClick={() => {
                    void continueWithRole(role)
                  }}
                  disabled={busy}
                >
                  {busy && busyRole === role ? 'Opening…' : label}
                </button>
              </div>
            )
          })}
        </div>

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