"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import { useState, useCallback } from "react";
import Link from "next/link";
import { useSearchParams, useRouter } from "next/navigation";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { useAuth } from "../../../hooks/useAuth";
import { Button } from "../../ui/button";
import { Input } from "../../ui/input";
import { Label } from "../../ui/label";
import { Alert, AlertDescription } from "../../ui/alert";
import { Checkbox } from "../../ui/checkbox";
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "../../ui/card";
import { Separator } from "../../ui/separator";
import { PasswordInput } from "../../ui/password-input";
import { Mail, User, Loader2, AlertCircle, ArrowRight, MailCheck, CheckCircle2, Users } from "lucide-react";
import { signupSchema } from "../../../lib/validation";
import { createTestId, sel } from "../../../lib/test";
import { useTranslations } from "next-intl";
import { AuthTranslationPreloader } from "../../../lib/i18n/AuthTranslationPreloader";
import { toast } from "sonner";
function SignupForm() {
  const router = useRouter();
  const [loadingProvider, setLoadingProvider] = useState(null);
  const [error, setError] = useState(null);
  const [agreedToTerms, setAgreedToTerms] = useState(false);
  const [emailSent, setEmailSent] = useState(false);
  const [registeredEmail, setRegisteredEmail] = useState("");
  const [resendingEmail, setResendingEmail] = useState(false);
  const [statusMessage, setStatusMessage] = useState("");
  const { signUp, googleSignIn, resendVerificationEmail } = useAuth();
  const t = useTranslations("auth");
  const searchParams = useSearchParams();
  const inviteEmail = searchParams.get("email");
  const fromInvite = searchParams.get("fromInvite") === "true";
  const callbackUrl = searchParams.get("callbackUrl");
  const inviteToken = searchParams.get("inviteToken");
  const {
    register,
    handleSubmit,
    watch,
    formState: { errors }
  } = useForm({
    resolver: zodResolver(signupSchema),
    defaultValues: {
      email: inviteEmail || ""
    }
  });
  const password = watch("password", "");
  const onSubmit = useCallback(async (data) => {
    var _a;
    if (!agreedToTerms) {
      setError(t("signup.errors.mustAgreeToTerms"));
      setStatusMessage(t("signup.messages.termsError"));
      return;
    }
    setLoadingProvider("email");
    setError(null);
    setStatusMessage(t("signup.messages.creatingAccount"));
    try {
      if (inviteToken) {
        const response = await fetch("/api/v1/auth/signup-with-invite", {
          method: "POST",
          headers: {
            "Content-Type": "application/json"
          },
          body: JSON.stringify({
            email: data.email,
            password: data.password,
            firstName: data.firstName,
            lastName: data.lastName,
            inviteToken
          })
        });
        const result = await response.json();
        if (!response.ok) {
          if (result.code === "USER_ALREADY_EXISTS") {
            setError("An account with this email already exists. Please sign in instead.");
          } else if (result.code === "EMAIL_MISMATCH") {
            setError("This invitation was sent to a different email address.");
          } else if (result.code === "INVITATION_EXPIRED") {
            setError("This invitation has expired. Please request a new one.");
          } else if (result.code === "INVITATION_NOT_FOUND") {
            setError("Invalid invitation. Please request a new one.");
          } else {
            setError(result.error || "Failed to create account");
          }
          setStatusMessage(t("signup.messages.createError", { error: result.error || "Unknown error" }));
          return;
        }
        toast.success("Account created successfully!", {
          description: "You have joined the team."
        });
        router.push(((_a = result.data) == null ? void 0 : _a.redirectTo) || "/dashboard/settings/teams");
        return;
      }
      await signUp({
        email: data.email,
        password: data.password,
        firstName: data.firstName,
        lastName: data.lastName
      });
      setRegisteredEmail(data.email);
      setEmailSent(true);
      setStatusMessage(t("signup.messages.accountCreated"));
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : "Failed to create account";
      setError(errorMessage);
      setStatusMessage(t("signup.messages.createError", { error: errorMessage }));
    } finally {
      setLoadingProvider(null);
    }
  }, [agreedToTerms, signUp, t, inviteToken, router]);
  const handleGoogleSignUp = async () => {
    setLoadingProvider("google");
    setError(null);
    try {
      await googleSignIn(callbackUrl || void 0);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Google sign up failed");
    } finally {
      setLoadingProvider(null);
    }
  };
  const handleResendEmail = async () => {
    setResendingEmail(true);
    setError(null);
    try {
      const result = await resendVerificationEmail(registeredEmail);
      if (result.success) {
        setEmailSent(true);
      } else {
        setError(result.error || "Failed to resend verification email");
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to resend verification email");
    } finally {
      setResendingEmail(false);
    }
  };
  if (emailSent) {
    return /* @__PURE__ */ jsxs(Fragment, { children: [
      /* @__PURE__ */ jsx(
        "div",
        {
          "aria-live": "polite",
          "aria-atomic": "true",
          className: "sr-only",
          ...createTestId("signup", "status", "message") && { "data-testid": createTestId("signup", "status", "message") },
          children: statusMessage
        }
      ),
      /* @__PURE__ */ jsxs(
        Card,
        {
          className: "w-full max-w-md",
          role: "main",
          "aria-labelledby": "email-sent-heading",
          ...createTestId("signup", "email-sent", "card") && { "data-testid": createTestId("signup", "email-sent", "card") },
          "data-cy": sel("auth.verifyEmail.container"),
          children: [
            /* @__PURE__ */ jsxs(
              CardHeader,
              {
                className: "space-y-1",
                ...createTestId("signup", "email-sent", "header") && { "data-testid": createTestId("signup", "email-sent", "header") },
                children: [
                  /* @__PURE__ */ jsx(
                    "div",
                    {
                      className: "mx-auto w-12 h-12 bg-green-100 rounded-full flex items-center justify-center mb-4",
                      role: "img",
                      "aria-label": "Email enviado exitosamente",
                      children: /* @__PURE__ */ jsx(MailCheck, { className: "w-6 h-6 text-green-600", "aria-hidden": "true" })
                    }
                  ),
                  /* @__PURE__ */ jsx(
                    CardTitle,
                    {
                      id: "email-sent-heading",
                      className: "text-2xl font-bold text-center",
                      ...createTestId("signup", "email-sent", "title") && { "data-testid": createTestId("signup", "email-sent", "title") },
                      children: t("signup.emailVerification.title")
                    }
                  ),
                  /* @__PURE__ */ jsx(
                    CardDescription,
                    {
                      className: "text-center",
                      ...createTestId("signup", "email-sent", "description") && { "data-testid": createTestId("signup", "email-sent", "description") },
                      children: t("signup.emailVerification.description")
                    }
                  )
                ]
              }
            ),
            /* @__PURE__ */ jsxs(CardContent, { className: "space-y-4", children: [
              /* @__PURE__ */ jsx("div", { className: "p-3 bg-muted rounded-lg", children: /* @__PURE__ */ jsx("p", { className: "text-sm font-medium text-center break-all", children: registeredEmail }) }),
              /* @__PURE__ */ jsxs(Alert, { "data-cy": sel("auth.verifyEmail.successMessage"), children: [
                /* @__PURE__ */ jsx(CheckCircle2, { className: "h-4 w-4" }),
                /* @__PURE__ */ jsx(AlertDescription, { children: "Please check your inbox and click the verification link to activate your account. The link will expire in 24 hours." })
              ] }),
              /* @__PURE__ */ jsxs("div", { className: "space-y-2 text-sm text-muted-foreground", children: [
                /* @__PURE__ */ jsxs("p", { className: "flex items-start gap-2", children: [
                  /* @__PURE__ */ jsx("span", { className: "text-primary font-medium", children: "1." }),
                  "Open your email inbox"
                ] }),
                /* @__PURE__ */ jsxs("p", { className: "flex items-start gap-2", children: [
                  /* @__PURE__ */ jsx("span", { className: "text-primary font-medium", children: "2." }),
                  "Find the email from us (check spam if needed)"
                ] }),
                /* @__PURE__ */ jsxs("p", { className: "flex items-start gap-2", children: [
                  /* @__PURE__ */ jsx("span", { className: "text-primary font-medium", children: "3." }),
                  "Click the verification button"
                ] })
              ] }),
              error && /* @__PURE__ */ jsxs(Alert, { variant: "destructive", children: [
                /* @__PURE__ */ jsx(AlertCircle, { className: "h-4 w-4" }),
                /* @__PURE__ */ jsx(AlertDescription, { children: error })
              ] }),
              /* @__PURE__ */ jsx(Separator, {}),
              /* @__PURE__ */ jsxs("div", { className: "text-center space-y-2", children: [
                /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: "Didn't receive the email?" }),
                /* @__PURE__ */ jsxs("div", { className: "flex gap-2", children: [
                  /* @__PURE__ */ jsxs(
                    Button,
                    {
                      variant: "outline",
                      onClick: () => {
                        setEmailSent(false);
                        setError(null);
                      },
                      className: "flex-1",
                      children: [
                        /* @__PURE__ */ jsx(ArrowRight, { className: "mr-2 h-4 w-4 rotate-180" }),
                        "Back"
                      ]
                    }
                  ),
                  /* @__PURE__ */ jsx(
                    Button,
                    {
                      variant: "default",
                      onClick: handleResendEmail,
                      disabled: resendingEmail,
                      className: "flex-1",
                      children: resendingEmail ? /* @__PURE__ */ jsxs(Fragment, { children: [
                        /* @__PURE__ */ jsx(Loader2, { className: "mr-2 h-4 w-4 animate-spin" }),
                        "Sending..."
                      ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
                        /* @__PURE__ */ jsx(Mail, { className: "mr-2 h-4 w-4" }),
                        "Resend Email"
                      ] })
                    }
                  )
                ] })
              ] })
            ] }),
            /* @__PURE__ */ jsx(CardFooter, { children: /* @__PURE__ */ jsxs("p", { className: "text-sm text-muted-foreground text-center w-full", children: [
              "Already verified?",
              " ",
              /* @__PURE__ */ jsx(Link, { href: "/login", className: "text-primary hover:underline font-medium", children: "Sign in" })
            ] }) })
          ]
        }
      )
    ] });
  }
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx(AuthTranslationPreloader, {}),
    /* @__PURE__ */ jsx(
      "div",
      {
        "aria-live": "polite",
        "aria-atomic": "true",
        className: "sr-only",
        ...createTestId("signup", "status", "message") && { "data-testid": createTestId("signup", "status", "message") },
        children: statusMessage
      }
    ),
    /* @__PURE__ */ jsxs(
      Card,
      {
        className: "w-full max-w-md",
        "data-testid": createTestId("signup", "card"),
        "data-cy": sel("auth.signup.form"),
        children: [
          /* @__PURE__ */ jsxs(
            CardHeader,
            {
              className: "space-y-1",
              ...createTestId("signup", "header") && { "data-testid": createTestId("signup", "header") },
              children: [
                /* @__PURE__ */ jsx(
                  CardTitle,
                  {
                    className: "text-2xl font-bold",
                    id: "signup-heading",
                    ...createTestId("signup", "title") && { "data-testid": createTestId("signup", "title") },
                    children: t("signup.title")
                  }
                ),
                /* @__PURE__ */ jsx(
                  CardDescription,
                  {
                    ...createTestId("signup", "description") && { "data-testid": createTestId("signup", "description") },
                    children: t("signup.description")
                  }
                )
              ]
            }
          ),
          /* @__PURE__ */ jsxs(CardContent, { children: [
            fromInvite && /* @__PURE__ */ jsxs(Alert, { className: "mb-4", "data-cy": "signup-invite-banner", children: [
              /* @__PURE__ */ jsx(Users, { className: "h-4 w-4" }),
              /* @__PURE__ */ jsx(AlertDescription, { children: t("signup.inviteBanner") })
            ] }),
            /* @__PURE__ */ jsxs("form", { onSubmit: handleSubmit(onSubmit), className: "space-y-4", children: [
              /* @__PURE__ */ jsxs("div", { className: "grid gap-4 sm:grid-cols-2", children: [
                /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
                  /* @__PURE__ */ jsx(Label, { htmlFor: "firstName", children: "First name" }),
                  /* @__PURE__ */ jsxs("div", { className: "relative", children: [
                    /* @__PURE__ */ jsx(User, { className: "absolute left-3 top-3 h-4 w-4 text-muted-foreground" }),
                    /* @__PURE__ */ jsx(
                      Input,
                      {
                        ...register("firstName"),
                        id: "firstName",
                        type: "text",
                        autoComplete: "given-name",
                        placeholder: "John",
                        className: "pl-9",
                        "data-cy": sel("auth.signup.firstName")
                      }
                    )
                  ] }),
                  errors.firstName && /* @__PURE__ */ jsx("p", { className: "text-sm text-destructive", children: errors.firstName.message })
                ] }),
                /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
                  /* @__PURE__ */ jsx(Label, { htmlFor: "lastName", children: "Last name" }),
                  /* @__PURE__ */ jsxs("div", { className: "relative", children: [
                    /* @__PURE__ */ jsx(User, { className: "absolute left-3 top-3 h-4 w-4 text-muted-foreground" }),
                    /* @__PURE__ */ jsx(
                      Input,
                      {
                        ...register("lastName"),
                        id: "lastName",
                        type: "text",
                        autoComplete: "family-name",
                        placeholder: "Doe",
                        className: "pl-9",
                        "data-cy": sel("auth.signup.lastName")
                      }
                    )
                  ] }),
                  errors.lastName && /* @__PURE__ */ jsx("p", { className: "text-sm text-destructive", children: errors.lastName.message })
                ] })
              ] }),
              /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
                /* @__PURE__ */ jsx(Label, { htmlFor: "email", children: "Email" }),
                /* @__PURE__ */ jsxs("div", { className: "relative", children: [
                  /* @__PURE__ */ jsx(Mail, { className: "absolute left-3 top-3 h-4 w-4 text-muted-foreground" }),
                  /* @__PURE__ */ jsx(
                    Input,
                    {
                      ...register("email"),
                      id: "email",
                      type: "email",
                      autoComplete: "email",
                      placeholder: "email@example.com",
                      className: `pl-9 ${fromInvite ? "bg-muted cursor-not-allowed" : ""}`,
                      readOnly: fromInvite,
                      "data-cy": sel("auth.signup.email")
                    }
                  )
                ] }),
                errors.email && /* @__PURE__ */ jsx("p", { className: "text-sm text-destructive", children: errors.email.message })
              ] }),
              /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
                /* @__PURE__ */ jsx(Label, { htmlFor: "password", children: "Password" }),
                /* @__PURE__ */ jsx(
                  PasswordInput,
                  {
                    ...register("password"),
                    id: "password",
                    autoComplete: "new-password",
                    placeholder: "\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",
                    showRequirements: true,
                    password,
                    "data-cy": sel("auth.signup.password")
                  }
                ),
                errors.password && /* @__PURE__ */ jsx("p", { className: "text-sm text-destructive", children: errors.password.message })
              ] }),
              /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
                /* @__PURE__ */ jsx(Label, { htmlFor: "confirmPassword", children: "Confirm password" }),
                /* @__PURE__ */ jsx(
                  PasswordInput,
                  {
                    ...register("confirmPassword"),
                    id: "confirmPassword",
                    autoComplete: "new-password",
                    placeholder: "\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",
                    "data-cy": sel("auth.signup.confirmPassword")
                  }
                ),
                errors.confirmPassword && /* @__PURE__ */ jsx("p", { className: "text-sm text-destructive", children: errors.confirmPassword.message })
              ] }),
              error && /* @__PURE__ */ jsxs(Alert, { variant: "destructive", children: [
                /* @__PURE__ */ jsx(AlertCircle, { className: "h-4 w-4" }),
                /* @__PURE__ */ jsx(AlertDescription, { children: error })
              ] }),
              /* @__PURE__ */ jsxs("div", { className: "flex items-center space-x-2", children: [
                /* @__PURE__ */ jsx(
                  Checkbox,
                  {
                    id: "terms",
                    checked: agreedToTerms,
                    onCheckedChange: (checked) => setAgreedToTerms(checked),
                    "data-cy": "signup-terms-checkbox"
                  }
                ),
                /* @__PURE__ */ jsxs(
                  Label,
                  {
                    htmlFor: "terms",
                    className: "text-sm font-normal cursor-pointer",
                    children: [
                      "I agree to the",
                      " ",
                      /* @__PURE__ */ jsx(Link, { href: "/terms", className: "text-primary hover:underline", children: "terms and conditions" })
                    ]
                  }
                )
              ] }),
              /* @__PURE__ */ jsx(
                Button,
                {
                  type: "submit",
                  disabled: !!loadingProvider || !agreedToTerms,
                  className: "w-full",
                  "data-cy": sel("auth.signup.submitButton"),
                  children: loadingProvider === "email" ? /* @__PURE__ */ jsxs(Fragment, { children: [
                    /* @__PURE__ */ jsx(Loader2, { className: "mr-2 h-4 w-4 animate-spin" }),
                    "Creating account..."
                  ] }) : "Create account"
                }
              )
            ] }),
            /* @__PURE__ */ jsxs("div", { className: "relative my-4", children: [
              /* @__PURE__ */ jsx("div", { className: "absolute inset-0 flex items-center", children: /* @__PURE__ */ jsx(Separator, { className: "w-full" }) }),
              /* @__PURE__ */ jsx("div", { className: "relative flex justify-center text-xs uppercase", children: /* @__PURE__ */ jsx("span", { className: "bg-background px-2 text-muted-foreground", children: "Or continue with" }) })
            ] }),
            /* @__PURE__ */ jsxs(
              Button,
              {
                type: "button",
                variant: "outline",
                onClick: handleGoogleSignUp,
                disabled: !!loadingProvider,
                className: "w-full",
                children: [
                  loadingProvider === "google" ? /* @__PURE__ */ jsx(Loader2, { className: "mr-2 h-4 w-4 animate-spin" }) : /* @__PURE__ */ jsxs("svg", { className: "mr-2 h-4 w-4", viewBox: "0 0 24 24", children: [
                    /* @__PURE__ */ jsx("path", { fill: "#4285F4", 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" }),
                    /* @__PURE__ */ jsx("path", { fill: "#34A853", 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" }),
                    /* @__PURE__ */ jsx("path", { fill: "#FBBC05", 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.93l2.85-2.22.81-.62z" }),
                    /* @__PURE__ */ jsx("path", { fill: "#EA4335", 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" })
                  ] }),
                  "Continue with Google"
                ]
              }
            )
          ] }),
          /* @__PURE__ */ jsx(
            CardFooter,
            {
              "data-testid": createTestId("signup", "footer"),
              "data-cy": "signup-footer",
              children: /* @__PURE__ */ jsxs("p", { className: "text-sm text-muted-foreground text-center w-full", children: [
                "Already have an account?",
                " ",
                /* @__PURE__ */ jsx(
                  Link,
                  {
                    href: "/login",
                    className: "text-primary hover:underline font-medium focus:outline-none focus:ring-2 focus:ring-accent",
                    "aria-label": "Ir a p\xE1gina de inicio de sesi\xF3n",
                    "data-testid": createTestId("signup", "login", "link"),
                    "data-cy": sel("auth.signup.loginLink"),
                    children: "Sign in"
                  }
                )
              ] })
            }
          )
        ]
      }
    )
  ] });
}
export {
  SignupForm
};
