"use client";

import { Suspense, useEffect } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { useState } from "react";

import { GoogleSignInButton } from "@/components/auth/google-sign-in-button";
import { GlassCard } from "@/components/shared/glass-card";
import { Button } from "@/components/ui/button";
import { ButtonLink } from "@/components/ui/button-link";
import { Input } from "@/components/ui/input";
import { PasswordInput } from "@/components/ui/password-input";
import { Label } from "@/components/ui/label";
import { Separator } from "@/components/ui/separator";
import { isCheckoutReturnPath, safeNextPath } from "@/lib/auth/safe-next-path";
import { toast } from "sonner";

const OAUTH_ERRORS: Record<string, string> = {
  google_not_configured: "Google sign-in is not available on this deployment.",
  google_denied: "Google sign-in was cancelled.",
  google_failed: "Google sign-in failed. Please try again or use email.",
};

function LoginFormInner() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const nextPath = safeNextPath(searchParams.get("next"));
  const checkoutGate = isCheckoutReturnPath(nextPath);
  const emailParam = searchParams.get("email") ?? "";
  const [email, setEmail] = useState(() => emailParam);
  const [password, setPassword] = useState("");
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    const err = searchParams.get("error");
    if (err && OAUTH_ERRORS[err]) {
      toast.error(OAUTH_ERRORS[err]);
      const url = new URL(window.location.href);
      url.searchParams.delete("error");
      window.history.replaceState({}, "", url.pathname + url.search);
    }
  }, [searchParams]);

  async function onSubmit(e: React.FormEvent) {
    e.preventDefault();
    setLoading(true);
    try {
      const res = await fetch("/api/auth/login", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email, password }),
      });
      const data = (await res.json().catch(() => ({}))) as {
        error?: string;
        code?: string;
      };
      if (!res.ok) {
        toast.error(typeof data.error === "string" ? data.error : "Login failed");
        if (data.code === "guest_checkout" || data.code === "password_required") {
          router.push(
            `/signup?from=purchase&email=${encodeURIComponent(email)}&next=${encodeURIComponent(nextPath)}`,
          );
        }
        return;
      }
      toast.success("Welcome back.");
      router.push(nextPath);
      router.refresh();
    } finally {
      setLoading(false);
    }
  }

  return (
    <GlassCard className="p-8 sm:p-9">
      <p className="text-primary text-xs font-semibold uppercase tracking-widest">Sign in</p>
      <h1 className="font-display mt-2 text-2xl font-semibold tracking-tight sm:text-3xl">
        {checkoutGate ? "Sign in to checkout" : "Continue to your dashboard"}
      </h1>
      <p className="text-muted-foreground mt-2 text-sm leading-relaxed">
        {checkoutGate
          ? "Sign in to complete your purchase. You will return to checkout to pay."
          : "Access plans, orders, downloads, and member support."}
      </p>

      <div className="mt-8 space-y-4">
        <GoogleSignInButton next={nextPath} />
        <div className="relative py-1">
          <Separator />
          <span className="bg-card text-muted-foreground absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 px-2 text-xs">
            or email
          </span>
        </div>
      </div>

      <form onSubmit={onSubmit} className="mt-6 space-y-4">
        <div>
          <Label htmlFor="email">Email</Label>
          <Input
            id="email"
            type="email"
            autoComplete="email"
            required
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            className="mt-2 h-11"
          />
        </div>
        <div>
          <Label htmlFor="password">Password</Label>
          <PasswordInput
            id="password"
            autoComplete="current-password"
            required
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            className="mt-2 h-11"
          />
        </div>
        <Button type="submit" disabled={loading} className="h-11 w-full rounded-xl">
          {loading ? "Signing in…" : "Sign in"}
        </Button>
      </form>
      <p className="text-muted-foreground mt-8 text-center text-sm">
        Bought without signing in?{" "}
        <ButtonLink
          href={`/signup?next=${encodeURIComponent(nextPath)}${email ? `&email=${encodeURIComponent(email)}` : ""}`}
          variant="link"
          className="px-0 font-medium"
        >
          Create account
        </ButtonLink>
      </p>
    </GlassCard>
  );
}

export function LoginForm() {
  return (
    <Suspense fallback={<GlassCard className="h-80 animate-pulse p-8" />}>
      <LoginFormInner />
    </Suspense>
  );
}
