"use client";

import { signIn } from "next-auth/react";
import Link from "next/link";
import { useSearchParams } from "next/navigation";
import { Suspense, useState } from "react";

function authErrorMessage(code: string | null): string | null {
  if (!code) return null;
  if (code === "Callback") {
    return (
      "Google could not complete sign-in. Most often: DATABASE_URL in vibn-frontend/.env.local must reach Postgres from " +
      "this machine (Coolify internal hostnames only work inside Docker). Use a public host/port, tunnel, or proxy; " +
      "then run npx prisma db push. Also confirm NEXTAUTH_URL matches the browser (http://localhost:3000) and " +
      "Google redirect URI http://localhost:3000/api/auth/callback/google. Dev check: GET /api/debug/prisma — see terminal for [next-auth] logs."
    );
  }
  if (code === "Configuration") {
    return "Auth is misconfigured (check GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, NEXTAUTH_SECRET).";
  }
  if (code === "AccessDenied") {
    return "Access was denied. You may need to be added as a test user if the OAuth app is in testing mode.";
  }
  return `Sign-in error: ${code}`;
}

const showDevLocalSignIn =
  process.env.NODE_ENV === "development" &&
  Boolean(process.env.NEXT_PUBLIC_DEV_LOCAL_AUTH_EMAIL?.trim());

function NextAuthForm() {
  const [isLoading, setIsLoading] = useState(false);
  const [devSecret, setDevSecret] = useState("");
  const searchParams = useSearchParams();
  const callbackUrl = searchParams.get("callbackUrl") ?? "/auth";
  const errorCode = searchParams.get("error");
  const errorHint = authErrorMessage(errorCode);

  const handleGoogleSignIn = async () => {
    setIsLoading(true);
    try {
      await signIn("google", { callbackUrl });
    } catch (error) {
      console.error("Google sign-in error:", error);
      setIsLoading(false);
    }
  };

  const handleDevLocalSignIn = async () => {
    setIsLoading(true);
    try {
      await signIn("dev-local", {
        callbackUrl,
        password: devSecret,
        redirect: true,
      });
    } catch (error) {
      console.error("Dev local sign-in error:", error);
      setIsLoading(false);
    }
  };

  // Detect new-vs-returning purely from local search params; we
  // don't have a session at this render path, but the homepage
  // sends "Get started" links with `?new=1` and "Sign in" links
  // without it. Fall back to neutral copy that works for both.
  const isNewUser = searchParams.get("new") === "1";
  const title = isNewUser ? "Create your account" : "Sign in or sign up";
  const subtitle = isNewUser
    ? "Continue with Google to set up your Vibn workspace."
    : "Continue with Google. New here? An account is created automatically on first sign-in.";

  return (
    <div className="justine-auth-inner">
      <div className="justine-auth-card">
        <h1 className="justine-auth-title f">{title}</h1>
        <p className="justine-auth-sub">{subtitle}</p>

        {errorHint && (
          <div
            role="alert"
            style={{
              marginBottom: 18,
              padding: "12px 14px",
              borderRadius: 10,
              fontSize: 12.5,
              lineHeight: 1.55,
              color: "#991B1B",
              background: "#FEF2F2",
              border: "1px solid #FECACA",
            }}
          >
            {errorHint}
          </div>
        )}

        <button
          type="button"
          className="justine-auth-btn-google"
          onClick={handleGoogleSignIn}
          disabled={isLoading}
        >
          <svg width={16} height={16} viewBox="0 0 24 24" fill="none" aria-hidden>
            <path
              d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"
              fill="#4285F4"
            />
            <path
              d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"
              fill="#34A853"
            />
            <path
              d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l3.66-2.84z"
              fill="#FBBC05"
            />
            <path
              d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"
              fill="#EA4335"
            />
          </svg>
          {isLoading ? "Signing in…" : "Continue with Google"}
        </button>

        {showDevLocalSignIn && (
          <div
            style={{
              marginTop: 22,
              paddingTop: 22,
              borderTop: "1px solid rgba(0,0,0,0.08)",
            }}
          >
            <p className="justine-auth-sub" style={{ marginBottom: 12 }}>
              Local only: sign in without Google as{" "}
              <strong>{process.env.NEXT_PUBLIC_DEV_LOCAL_AUTH_EMAIL}</strong>
            </p>
            <form
              onSubmit={(e) => {
                e.preventDefault();
                void handleDevLocalSignIn();
              }}
            >
              <input
                type="password"
                name="dev-local-secret"
                autoComplete="current-password"
                placeholder="Dev secret (only if DEV_LOCAL_AUTH_SECRET is set)"
                value={devSecret}
                onChange={(e) => setDevSecret(e.target.value)}
                className="justine-auth-dev-input"
                style={{
                  width: "100%",
                  marginBottom: 10,
                  padding: "10px 12px",
                  borderRadius: 8,
                  border: "1px solid rgba(0,0,0,0.12)",
                  fontSize: 14,
                }}
              />
              <button
                type="submit"
                className="justine-auth-btn-google"
                disabled={isLoading}
                style={{
                  background: "#111827",
                  color: "#fff",
                }}
              >
                {isLoading ? "Signing in…" : "Continue (local dev account)"}
              </button>
            </form>
          </div>
        )}

        <p className="justine-auth-legal">
          By continuing, you agree to our{" "}
          <Link href="/terms">Terms</Link> and <Link href="/privacy">Privacy Policy</Link>.
        </p>
      </div>
    </div>
  );
}

function NextAuthFallback() {
  return (
    <div className="justine-auth-inner">
      <div className="justine-auth-loading-wrap">
        <div className="justine-auth-spinner" aria-hidden />
        <p className="justine-auth-loading-text">Loading…</p>
      </div>
    </div>
  );
}

export default function NextAuthComponent() {
  return (
    <Suspense fallback={<NextAuthFallback />}>
      <NextAuthForm />
    </Suspense>
  );
}
