"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import { useTranslations } from "next-intl";
import { authClient } from "@/lib/auth/client";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
import { Separator } from "@/components/ui/separator";

const INVITE_COOKIE = "epicure_invite";

export function SignupForm({ signupsDisabled, inviteToken }: { signupsDisabled: boolean; inviteToken: string | null }) {
  const router = useRouter();
  const t = useTranslations("auth");
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [loading, setLoading] = useState(false);
  const [inviteState, setInviteState] = useState<"checking" | "valid" | "invalid" | "none">(
    inviteToken ? "checking" : "none"
  );
  const [inviteEmail, setInviteEmail] = useState<string | null>(null);

  useEffect(() => {
    if (!inviteToken) return;
    fetch(`/api/v1/invites/${inviteToken}`)
      .then((res) => res.json())
      .then((data: { valid: boolean; email: string | null }) => {
        setInviteState(data.valid ? "valid" : "invalid");
        if (data.valid && data.email) {
          setInviteEmail(data.email);
          setEmail(data.email);
        }
      })
      .catch(() => setInviteState("invalid"));
  }, [inviteToken]);

  function setInviteCookie() {
    if (inviteToken && inviteState === "valid") {
      document.cookie = `${INVITE_COOKIE}=${inviteToken}; path=/; max-age=600; samesite=lax`;
    }
  }

  const locked = signupsDisabled && inviteState !== "valid";

  async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setLoading(true);
    setInviteCookie();
    const { error } = await authClient.signUp.email({
      name,
      email,
      password,
      callbackURL: "/recipes",
    });
    setLoading(false);
    if (error) {
      toast.error(error.message ?? "Sign up failed");
    } else {
      toast.success("Account created — check your email to verify");
      router.push("/login");
    }
  }

  async function handleGoogle() {
    setInviteCookie();
    await authClient.signIn.social({ provider: "google", callbackURL: "/recipes" });
  }

  if (signupsDisabled && inviteState === "checking") {
    return (
      <Card>
        <CardContent className="py-10 text-center text-muted-foreground">Checking invite…</CardContent>
      </Card>
    );
  }

  if (signupsDisabled && inviteState === "none") {
    return (
      <Card>
        <CardHeader className="space-y-1">
          <CardTitle className="text-2xl font-semibold tracking-tight">Signups are closed</CardTitle>
          <CardDescription>Epicure isn&apos;t accepting new accounts right now. You&apos;ll need an invite link.</CardDescription>
        </CardHeader>
        <CardFooter className="flex justify-center">
          <Link href="/login" className="text-sm underline underline-offset-4 hover:text-foreground">
            Back to login
          </Link>
        </CardFooter>
      </Card>
    );
  }

  if (signupsDisabled && inviteState === "invalid") {
    return (
      <Card>
        <CardHeader className="space-y-1">
          <CardTitle className="text-2xl font-semibold tracking-tight">Invite invalid or expired</CardTitle>
          <CardDescription>This invite link no longer works. Ask whoever sent it for a new one.</CardDescription>
        </CardHeader>
        <CardFooter className="flex justify-center">
          <Link href="/login" className="text-sm underline underline-offset-4 hover:text-foreground">
            Back to login
          </Link>
        </CardFooter>
      </Card>
    );
  }

  return (
    <Card>
      <CardHeader className="space-y-1">
        <CardTitle className="text-2xl font-semibold tracking-tight">{t("signUpTitle")}</CardTitle>
        <CardDescription>{t("signUpSubtitle")}</CardDescription>
      </CardHeader>
      <form onSubmit={handleSubmit}>
        <CardContent className="space-y-4">
          <Button variant="outline" className="w-full" type="button" onClick={() => { void handleGoogle(); }} disabled={locked}>
            {t("continueWithGoogle")}
          </Button>
          <div className="flex items-center gap-2">
            <Separator className="flex-1" />
            <span className="text-xs text-muted-foreground">{t("or")}</span>
            <Separator className="flex-1" />
          </div>
          <div className="space-y-2">
            <Label htmlFor="name">{t("name")}</Label>
            <Input id="name" type="text" placeholder={t("namePlaceholder")} value={name} onChange={(e) => setName(e.target.value)} required />
          </div>
          <div className="space-y-2">
            <Label htmlFor="email">{t("email")}</Label>
            <Input
              id="email"
              type="email"
              placeholder={t("emailPlaceholder")}
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              readOnly={!!inviteEmail}
              required
            />
          </div>
          <div className="space-y-2">
            <Label htmlFor="password">{t("password")}</Label>
            <Input id="password" type="password" value={password} onChange={(e) => setPassword(e.target.value)} required minLength={8} />
          </div>
          <Button className="w-full" type="submit" disabled={loading || locked}>
            {loading ? t("signUpLoading") : t("signUpTitle")}
          </Button>
        </CardContent>
      </form>
      <CardFooter className="flex justify-center">
        <p className="text-sm text-muted-foreground">
          {t("alreadyHaveAccount")}{" "}
          <Link href="/login" className="underline underline-offset-4 hover:text-foreground">{t("signIn")}</Link>
        </p>
      </CardFooter>
    </Card>
  );
}
