"use client";

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

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

function SignupForm() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const fromPurchase = searchParams.get("from") === "purchase";
  const emailParam = searchParams.get("email") ?? "";
  const nextPath = safeNextPath(searchParams.get("next"));
  const checkoutGate = isCheckoutReturnPath(nextPath);

  const [name, setName] = useState("");
  const [email, setEmail] = useState(() => emailParam);
  const [password, setPassword] = useState("");
  const [loading, setLoading] = useState(false);

  async function onSubmit(e: React.FormEvent) {
    e.preventDefault();
    setLoading(true);
    try {
      const res = await fetch("/api/auth/register", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ name, email, password }),
      });
      const data = (await res.json().catch(() => ({}))) as {
        error?: string;
        claimed?: boolean;
      };
      if (!res.ok) {
        toast.error(typeof data.error === "string" ? data.error : "Could not register");
        return;
      }
      toast.success(
        data.claimed
          ? "Password set — your purchased plans are on your dashboard."
          : "Account created — welcome.",
      );
      router.push(checkoutGate ? nextPath : "/dashboard?welcome=1");
      router.refresh();
    } finally {
      setLoading(false);
    }
  }

  return (
    <GlassCard className="p-8 sm:p-9">
      <p className="text-primary text-xs font-semibold uppercase tracking-widest">
        {fromPurchase ? "Finish your account" : "Create account"}
      </p>
      <h1 className="font-display mt-2 text-2xl font-semibold tracking-tight sm:text-3xl">
        {fromPurchase ? "Set a password for your plans" : "Start your member profile"}
      </h1>
      <p className="text-muted-foreground mt-2 text-sm leading-relaxed">
        {checkoutGate ? (
          "Create an account to pay. After signup you return to checkout — Google works too."
        ) : fromPurchase ? (
          <>
            Use the <strong className="text-foreground">same email as checkout</strong>. Your
            purchase is already linked — you only need a password to sign in again later.
          </>
        ) : (
          "Track purchases, unlock plans, and reach your coach on WhatsApp from the dashboard."
        )}
      </p>

      <div className="mt-8 space-y-4">
        <GoogleSignInButton label="Continue with Google" 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="name">Name</Label>
          <Input
            id="name"
            required
            value={name}
            onChange={(e) => setName(e.target.value)}
            className="mt-2 h-11"
          />
        </div>
        <div>
          <Label htmlFor="email">Email</Label>
          <Input
            id="email"
            type="email"
            required
            readOnly={Boolean(fromPurchase && emailParam)}
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            className="mt-2 h-11"
          />
        </div>
        <div>
          <Label htmlFor="password">Password</Label>
          <PasswordInput
            id="password"
            minLength={6}
            required
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            className="mt-2 h-11"
            placeholder="At least 6 characters"
          />
        </div>
        <Button type="submit" disabled={loading} className="h-11 w-full rounded-xl">
          {loading
            ? "Saving…"
            : fromPurchase
              ? "Set password & open dashboard"
              : "Create account"}
        </Button>
      </form>
      <p className="text-muted-foreground mt-8 text-center text-sm">
        Already set a password?{" "}
        <ButtonLink
          href={`/login?next=${encodeURIComponent(nextPath)}${email ? `&email=${encodeURIComponent(email)}` : ""}`}
          variant="link"
          className="px-0 font-medium"
        >
          Sign in
        </ButtonLink>
      </p>
    </GlassCard>
  );
}

export default function SignupPage() {
  return (
    <Suspense fallback={<GlassCard className="h-[28rem] animate-pulse p-8" />}>
      <SignupForm />
    </Suspense>
  );
}
