"use client";

import { useRouter } from "next/navigation";
import { useState } from "react";

import PasswordFields from "@/components/admin/PasswordFields";
import { api } from "@/lib/api/browser";

/**
 * The confined session's only screen (design D14).
 *
 * Navigation is reduced to this and signing out, because everything else would be refused —
 * offering a route the API will turn down is worse than not offering it. The session that
 * performs the change keeps working: the API re-issues its cookie in the same response, so
 * the admin is not signed out of the browser they just used to do the right thing.
 */
export default function ForcedPasswordChange({ email }: { email: string }) {
  const router = useRouter();
  const [signingOut, setSigningOut] = useState(false);

  return (
    <>
      <p className="mt-4 rounded-lg border border-stone-200 bg-white px-3 py-2 text-sm text-stone-600">
        Signed in as <span className="font-medium text-stone-900">{email}</span>
      </p>

      <PasswordFields
        submitLabel="Set password and continue"
        onChanged={() => {
          // Refresh rather than push: the server layout re-reads the session, sees the
          // confinement lifted, and stops redirecting here.
          router.replace("/admin");
          router.refresh();
        }}
      />

      <button
        type="button"
        disabled={signingOut}
        onClick={async () => {
          setSigningOut(true);
          try {
            await api.signOut();
          } finally {
            router.replace("/admin/signin");
            router.refresh();
          }
        }}
        className="mt-4 self-start text-sm text-stone-600 underline-offset-2 hover:text-stone-900 hover:underline disabled:opacity-50"
      >
        {signingOut ? "Signing out…" : "Sign out instead"}
      </button>
    </>
  );
}
