"use client";

import { AlertCircle, Loader2 } from "lucide-react";
import { useTranslations } from "next-intl";
import { useState } from "react";
import { toast } from "sonner";

import { Alert, AlertDescription } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Link, useRouter } from "@/i18n/navigation";
import { authClient } from "@/lib/auth-client";
import { cn } from "@/lib/utils";

function isEmailRelatedError(message: string): boolean {
  const lower = message.toLowerCase();
  return (
    lower.includes("email") ||
    lower.includes("gmail") ||
    lower.includes("icloud") ||
    lower.includes("outlook") ||
    lower.includes("domaine") ||
    lower.includes("jetable") ||
    lower.includes("professionnel")
  );
}

export function SignupForm({ className, ...props }: React.ComponentProps<"div">) {
  const router = useRouter();
  const t = useTranslations("Auth.signup");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setLoading(true);
    setError(null);

    const form = new FormData(e.currentTarget);
    const name = form.get("name") as string;
    const email = form.get("email") as string;
    const password = form.get("password") as string;

    await authClient.signUp.email(
      { name, email, password, callbackURL: "/dashboard" },
      {
        onSuccess() {
          toast.success(t("successToast"));
          router.push("/dashboard");
        },
        onError(ctx) {
          const message = ctx.error.message || t("errorFallback");
          setError(message);
          toast.error(message);
          setLoading(false);
        },
      },
    );
  }

  const emailError = error && isEmailRelatedError(error);

  return (
    <div className={cn("flex flex-col gap-6", className)} {...props}>
      <Card>
        <CardHeader>
          <CardTitle>{t("title")}</CardTitle>
          <CardDescription>{t("description")}</CardDescription>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleSubmit}>
            <div className="flex flex-col gap-6">
              {error && (
                <Alert variant="destructive">
                  <AlertCircle />
                  <AlertDescription>{error}</AlertDescription>
                </Alert>
              )}
              <div className="grid gap-3">
                <Label htmlFor="name">{t("nameLabel")}</Label>
                <Input
                  id="name"
                  name="name"
                  type="text"
                  placeholder={t("namePlaceholder")}
                  required
                  autoComplete="name"
                />
              </div>
              <div className="grid gap-3">
                <Label htmlFor="email">{t("emailLabel")}</Label>
                <Input
                  id="email"
                  name="email"
                  type="email"
                  placeholder={t("emailPlaceholder")}
                  required
                  autoComplete="email"
                  aria-invalid={emailError ? true : undefined}
                  className={cn(
                    emailError && "border-destructive focus-visible:ring-destructive/30",
                  )}
                />
                <p className="text-sm text-muted-foreground">{t("emailHint")}</p>
              </div>
              <div className="grid gap-3">
                <Label htmlFor="password">{t("passwordLabel")}</Label>
                <Input
                  id="password"
                  name="password"
                  type="password"
                  placeholder="••••••••"
                  required
                  minLength={8}
                  autoComplete="new-password"
                />
              </div>
              <Button type="submit" disabled={loading} className="w-full">
                {loading ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : null}
                {t("submit")}
              </Button>
            </div>
            <div className="mt-4 text-center text-sm">
              {t("hasAccount")}{" "}
              <Link href="/login" className="underline underline-offset-4">
                {t("signIn")}
              </Link>
            </div>
          </form>
        </CardContent>
      </Card>
      <p className="text-center text-xs text-muted-foreground">
        {t("seePricingPrompt")}{" "}
        <Link href="/pricing" className="text-primary hover:underline">
          {t("seePricingLink")}
        </Link>
      </p>
    </div>
  );
}
