import { FormEvent, useState } from "react";

type PrivilegedGateProps = {
  error?: string | null;
  isPending?: boolean;
  onUnlock: (accessToken: string) => Promise<unknown>;
};

export function PrivilegedGate({ error = null, isPending = false, onUnlock }: PrivilegedGateProps) {
  const [accessToken, setAccessToken] = useState("");

  const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    await onUnlock(accessToken);
  };

  return (
    <main className="flex min-h-screen items-center justify-center p-6">
      <div className="w-full max-w-md rounded-3xl border border-border bg-card p-10 shadow-sm">
        <p className="text-sm uppercase tracking-[0.25em] text-foreground/60">Internal Only</p>
        <h1 className="mt-4 text-3xl font-semibold">Admin access token required</h1>
        <p className="mt-3 text-sm text-foreground/70">
          Normal XTablo login is not sufficient. Enter a privileged access token to unlock the
          internal admin dashboard.
        </p>

        <form className="mt-8 space-y-4" onSubmit={handleSubmit}>
          <label className="block text-sm font-medium" htmlFor="admin-access-token">
            Access token
          </label>
          <input
            id="admin-access-token"
            className="w-full rounded-2xl border border-border bg-background px-4 py-3"
            onChange={(event) => setAccessToken(event.target.value)}
            value={accessToken}
          />

          {error ? <p className="text-sm text-red-600">{error}</p> : null}

          <button
            className="w-full rounded-2xl bg-foreground px-4 py-3 text-background disabled:opacity-60"
            disabled={isPending || accessToken.trim().length === 0}
            type="submit"
          >
            {isPending ? "Unlocking..." : "Unlock Admin"}
          </button>
        </form>
      </div>
    </main>
  );
}
