"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());

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

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);
    }
  };

  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
      style={{
        width: "100%",
        maxWidth: "440px",
        margin: "0 auto",
        position: "relative",
        zIndex: 10,
      }}
    >
      {/* Logo */}
      <div
        style={{
          display: "flex",
          justifyContent: "center",
          marginBottom: "32px",
        }}
      >
        <span className="logo" style={{ fontSize: "20px" }}>
          <a
            href="/"
            style={{
              display: "inline-flex",
              alignItems: "center",
              gap: "9px",
              textDecoration: "none",
              color: "inherit",
            }}
          >
            <span
              className="logo-mark"
              style={{
                width: "32px",
                height: "32px",
                borderRadius: "50%",
                background:
                  "linear-gradient(135deg, var(--accent) 0%, oklch(0.65 0.20 18) 100%)",
                boxShadow:
                  "0 0 22px var(--accent-glow), inset 0 1px 0 oklch(1 0 0 / 0.25)",
                display: "grid",
                placeItems: "center",
                color: "var(--accent-fg)",
                flexShrink: 0,
              }}
            >
              <svg
                viewBox="0 0 36 32"
                width="74%"
                height="74%"
                fill="currentColor"
                stroke="currentColor"
                strokeWidth="1.2"
                strokeLinejoin="round"
                aria-hidden="true"
              >
                <path d="M4 5 L10 5 L12 18 L14 5 L20 5 L12 27 Z" />
                <rect
                  x="22.5"
                  y="23"
                  width="9.5"
                  height="3.8"
                  rx="0.7"
                  className="logo-caret"
                />
              </svg>
            </span>
            <span>vibn</span>
          </a>
        </span>
      </div>

      {/* Card */}
      <div
        className="card"
        style={{
          padding: "40px 32px",
          display: "flex",
          flexDirection: "column",
          gap: "24px",
        }}
      >
        <div style={{ textAlign: "center" }}>
          <h1
            style={{
              fontSize: "24px",
              fontWeight: 600,
              letterSpacing: "-0.02em",
              color: "var(--fg)",
              marginBottom: "8px",
            }}
          >
            {title}
          </h1>
          <p
            style={{
              fontSize: "15px",
              color: "var(--fg-dim)",
              lineHeight: 1.5,
            }}
          >
            {subtitle}
          </p>
        </div>

        {errorHint && (
          <div
            role="alert"
            style={{
              padding: "12px 14px",
              borderRadius: 10,
              fontSize: 13,
              lineHeight: 1.55,
              color: "#ffae9a",
              background: "oklch(0.74 0.175 35 / 0.15)",
              border: "1px solid oklch(0.74 0.175 35 / 0.3)",
            }}
          >
            {errorHint}
          </div>
        )}

        <button
          type="button"
          className="btn btn-ghost"
          style={{
            width: "100%",
            justifyContent: "center",
            height: "48px",
            fontSize: "15px",
            gap: "12px",
          }}
          onClick={handleGoogleSignIn}
          disabled={isLoading}
        >
          <svg
            width={18}
            height={18}
            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: 8,
              paddingTop: 24,
              borderTop: "1px solid var(--hairline)",
            }}
          >
            <p
              style={{
                fontSize: "13px",
                color: "var(--fg-dim)",
                marginBottom: 12,
                textAlign: "center",
              }}
            >
              Local only: sign in without Google as <br />
              <strong style={{ color: "var(--fg)" }}>
                {process.env.NEXT_PUBLIC_DEV_LOCAL_AUTH_EMAIL}
              </strong>
            </p>
            <form
              onSubmit={(e) => {
                e.preventDefault();
                void handleDevLocalSignIn();
              }}
              style={{ display: "flex", gap: 8 }}
            >
              <input
                type="password"
                name="dev-local-secret"
                autoComplete="current-password"
                placeholder="Dev secret"
                value={devSecret}
                onChange={(e) => setDevSecret(e.target.value)}
                style={{
                  flex: 1,
                  padding: "0 14px",
                  height: "40px",
                  borderRadius: "8px",
                  background: "oklch(0.16 0.008 60)",
                  border: "1px solid var(--hairline)",
                  color: "var(--fg)",
                  fontSize: "14px",
                  outline: "none",
                }}
              />
              <button
                type="submit"
                disabled={isLoading}
                className="btn btn-primary"
                style={{
                  height: "40px",
                  padding: "0 16px",
                  borderRadius: "8px",
                }}
              >
                Sign in
              </button>
            </form>
          </div>
        )}
      </div>

      <div
        style={{
          textAlign: "center",
          fontSize: "12px",
          color: "var(--fg-faint)",
          marginTop: "24px",
          lineHeight: 1.5,
        }}
      >
        By continuing, you agree to Vibn's{" "}
        <a
          href="#"
          style={{ color: "var(--fg-dim)", textDecoration: "underline" }}
        >
          Terms of Service
        </a>{" "}
        and{" "}
        <a
          href="#"
          style={{ color: "var(--fg-dim)", textDecoration: "underline" }}
        >
          Privacy Policy
        </a>
        .
      </div>
    </div>
  );
}
