"use client";

import { useEffect, useState } from "react";
import { ApiError, get, put } from "@/lib/api";
import { Badge, Field, Notice, Spinner } from "@/components/ui";

type GoogleStatus = {
  clientId: string;
  clientSecretSet: boolean;
  configured: boolean;
};

export default function GoogleAuthSettings() {
  const [data, setData] = useState<GoogleStatus | null>(null);
  const [clientId, setClientId] = useState("");
  const [clientSecret, setClientSecret] = useState("");
  const [errors, setErrors] = useState<string[]>([]);
  const [saved, setSaved] = useState(false);
  const [busy, setBusy] = useState(false);
  const [loadError, setLoadError] = useState<string | null>(null);
  const [redirectUri, setRedirectUri] = useState("");

  function hydrate(d: GoogleStatus) {
    setData(d);
    setClientId(d.clientId);
    setClientSecret("");
  }

  useEffect(() => {
    get<GoogleStatus>("google-auth").then(hydrate).catch((e) => setLoadError((e as Error).message));
    if (typeof window !== "undefined") setRedirectUri(`${window.location.origin}/api/auth/google/callback`);
  }, []);

  if (loadError) return <Notice kind="error">Could not load Google Auth config: {loadError}</Notice>;
  if (!data) return <Spinner label="Loading Google Auth configuration…" />;

  async function save(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setBusy(true);
    setSaved(false);
    setErrors([]);
    const payload: Record<string, unknown> = { clientId };
    if (clientSecret !== "") payload.clientSecret = clientSecret;
    try {
      hydrate(await put<GoogleStatus>("google-auth", payload));
      setSaved(true);
    } catch (err) {
      setErrors(err instanceof ApiError && err.errors.length ? err.errors : [(err as Error).message]);
    } finally {
      setBusy(false);
    }
  }

  return (
    <section aria-labelledby="google-h" className="space-y-6">
      <h2 id="google-h" className="text-xl font-semibold text-slate-900">Google sign-in (OAuth)</h2>
      <p className="-mt-4 text-sm text-slate-600">
        Lets users sign in with Google. Create an OAuth 2.0 Client (type “Web application”) in the Google Cloud Console and
        paste its credentials here. Who is allowed to sign in — and the roles they get — is managed under{" "}
        <strong>Users &amp; Roles</strong>.
      </p>

      {saved && <Notice kind="success">Google Auth configuration saved.</Notice>}
      {errors.length > 0 && <Notice kind="error"><ul className="list-disc pl-5">{errors.map((er, i) => <li key={i}>{er}</li>)}</ul></Notice>}

      <Notice kind="info">
        Add this exact <strong>Authorized redirect URI</strong> to your Google OAuth client:{" "}
        <code className="break-all">{redirectUri || "…/api/auth/google/callback"}</code>
      </Notice>

      <form onSubmit={save} className="space-y-6">
        <div className="card grid gap-5 sm:grid-cols-2">
          <Field label="Client ID" htmlFor="g-client-id" hint="…apps.googleusercontent.com">
            <input id="g-client-id" value={clientId} onChange={(e) => setClientId(e.target.value)} className="input font-mono text-xs" autoComplete="off" />
          </Field>
          <Field
            label="Client secret"
            htmlFor="g-client-secret"
            hint={data.clientSecretSet ? "A secret is stored. Leave blank to keep it." : "Paste the OAuth client secret."}
          >
            <input
              id="g-client-secret"
              type="password"
              value={clientSecret}
              onChange={(e) => setClientSecret(e.target.value)}
              placeholder={data.clientSecretSet ? "•••••••• (set)" : "not set"}
              className="input"
              autoComplete="new-password"
            />
          </Field>
        </div>

        <p className="text-xs text-slate-500">
          Status: {data.configured ? <Badge kind="ok">configured</Badge> : <Badge kind="warn">incomplete</Badge>}{" "}
          · client secret {data.clientSecretSet ? "set" : "not set"}. The secret is write-only.
        </p>

        <button type="submit" className="btn-primary" disabled={busy}>{busy ? "Saving…" : "Save Google sign-in"}</button>
      </form>
    </section>
  );
}
