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

/** CI `user/welcome_back.php` — multi-role picker (same behavior as `/app/select-role`). */
export function WelcomeBackPage() {
  const { user, roles } = useAuth()
  const { continueWithRole, busy, busyRole, error } = useContinueWithRole()

  return (
    <div className="container-fluid py-4 px-3">
      <div className="row g-4 justify-content-center align-items-stretch">
        <div className="col-12 col-md-5 col-lg-4 d-flex flex-column align-items-center justify-content-center border rounded p-4 bg-light">
          <img
            src="/images/logo.png"
            alt=""
            className="img-fluid mb-3"
            style={{ maxWidth: 200 }}
            onError={(ev) => {
              ;(ev.target as HTMLImageElement).style.display = 'none'
            }}
          />
          <div className="fw-semibold text-center">Al Rahma Sunday School</div>
        </div>
        <div className="col-12 col-md-6 col-lg-5">
          <div className="border rounded p-4 shadow-sm h-100">
            <h2 className="h4 mb-3">Welcome back!</h2>
            <p className="text-muted small mb-4">
              As your account has multiple roles in the portal, select how you want to continue:
            </p>
            <div className="d-flex flex-column gap-2">
              {roles.map((role) => {
                const label = role.replace(/_/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase())
                return (
                  <button
                    key={role}
                    type="button"
                    className="btn btn-success"
                    disabled={busy}
                    onClick={() => void continueWithRole(role)}
                  >
                    {busy && busyRole === role ? 'Opening…' : label}
                  </button>
                )
              })}
            </div>
            {user?.name ? (
              <p className="small text-muted mt-3 mb-0">Signed in as {user.name}</p>
            ) : null}
            {error ? <div className="alert alert-danger mt-3 mb-0 py-2 small">{error}</div> : null}
            <div className="mt-4 text-center">
              <Link className="small" to="/app/select-role">
                Alternative layout (same action)
              </Link>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}
