"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="auth-card card">
        <style>{`
          .auth-card {
            position: relative;
            z-index: 2;
            width: 100%; max-width: 440px;
            padding: 36px clamp(24px, 4vw, 40px) 32px;
            background: linear-gradient(180deg, oklch(0.20 0.009 60 / 0.85), oklch(0.17 0.008 60 / 0.85));
            border: 1px solid var(--hairline);
            border-radius: 22px;
            backdrop-filter: blur(20px);
            box-shadow:
              0 30px 80px -20px oklch(0 0 0 / 0.7),
              0 0 80px -30px var(--accent-glow);
            display: flex;
            flex-direction: column;
            gap: 24px;
          }
          .auth-card::before {
            content: "";
            position: absolute; left: 0; right: 0; top: 0; height: 1px;
            background: linear-gradient(90deg, transparent, var(--accent), transparent);
            opacity: .6;
          }
          .auth-eye {
            display: inline-flex; align-items: center; gap: 8px;
            font-family: var(--font-mono);
            font-size: 11px; letter-spacing: 0.14em; text-transform: uppercase;
            color: var(--fg-mute);
          }
          .auth-eye::before {
            content: ""; width: 5px; height: 5px; border-radius: 50%;
            background: var(--accent); box-shadow: 0 0 12px var(--accent-glow);
          }
          .auth-title {
            margin-top: 14px;
            font-size: clamp(26px, 3.4vw, 34px);
            font-weight: 500;
            letter-spacing: -0.022em;
            line-height: 1.1;
            text-wrap: balance;
          }
          .auth-title em {
            font-style: normal;
            color: var(--accent);
            text-shadow: 0 0 30px var(--accent-glow);
          }
          .auth-sub {
            margin-top: 10px;
            color: var(--fg-mute);
            font-size: 14.5px;
            line-height: 1.5;
            text-wrap: balance;
          }
        `}</style>
        {/* Glows */}
        <div
          style={{
            position: "absolute",
            inset: 0,
            overflow: "hidden",
            pointerEvents: "none",
            borderRadius: "inherit",
          }}
        >
          <div
            style={{
              position: "absolute",
              top: "-20%",
              left: "-10%",
              width: "50%",
              height: "50%",
              background: "var(--accent)",
              filter: "blur(80px)",
              opacity: 0.15,
            }}
          />
          <div
            style={{
              position: "absolute",
              bottom: "-20%",
              right: "-10%",
              width: "50%",
              height: "50%",
              background: "oklch(0.65 0.20 18)",
              filter: "blur(80px)",
              opacity: 0.15,
            }}
          />
        </div>

        <div style={{ position: "relative", zIndex: 2 }}>
          <div className="auth-eye">Welcome back</div>
          <h1 className="auth-title">
            Sign in and <em>keep building</em>.
          </h1>
          <p className="auth-sub">{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="auth-btn-ghost"
          style={{
            display: "inline-flex",
            alignItems: "center",
            justifyContent: "center",
            gap: "10px",
            height: "50px",
            padding: "0 22px",
            borderRadius: "999px",
            fontWeight: 500,
            fontSize: "15px",
            transition:
              "transform .12s, box-shadow .2s, background .2s, color .15s",
            whiteSpace: "nowrap",
            width: "100%",
            background: "oklch(0.20 0.009 60 / 0.6)",
            border: "1px solid var(--hairline)",
            color: "var(--fg-dim)",
            cursor: "pointer",
          }}
          onMouseEnter={(e) => {
            e.currentTarget.style.color = "var(--fg)";
            e.currentTarget.style.borderColor = "var(--hairline-2)";
            e.currentTarget.style.background = "oklch(0.22 0.010 60 / 0.8)";
          }}
          onMouseLeave={(e) => {
            e.currentTarget.style.color = "var(--fg-dim)";
            e.currentTarget.style.borderColor = "var(--hairline)";
            e.currentTarget.style.background = "oklch(0.20 0.009 60 / 0.6)";
          }}
          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>
  );
}
