"use client";

import type {Route} from "next";
import Link from "next/link";
import {useRouter} from "next/navigation";
import {useState, useTransition} from "react";
import {zodResolver} from "@hookform/resolvers/zod";
import {useForm} from "react-hook-form";
import {signIn} from "next-auth/react";
import {z} from "zod";
import {AuthCard} from "@/components/auth/auth-card";
import {Alert} from "@/components/ui/alert";
import {Button} from "@/components/ui/button";
import {Input} from "@/components/ui/input";
import {Label} from "@/components/ui/label";
import {APP_ROUTES} from "@/lib/constants/routes";
import {signUpSchema} from "@/lib/validations/auth";

type SignUpFormProps = {
  locale: string;
};

type FormValues = z.input<typeof signUpSchema>;

export function SignUpForm({locale}: SignUpFormProps) {
  const router = useRouter();
  const [isPending, startTransition] = useTransition();
  const [message, setMessage] = useState<string | null>(null);
  const [errorMessage, setErrorMessage] = useState<string | null>(null);
  const form = useForm<FormValues>({
    resolver: zodResolver(signUpSchema),
    defaultValues: {
      firstName: "",
      lastName: "",
      email: "",
      password: "",
      confirmPassword: "",
      preferredLanguage: locale === "ar" ? "ar" : "en",
      tenantSlug: ""
    }
  });

  const onSubmit = (values: FormValues) => {
    setMessage(null);
    setErrorMessage(null);

    startTransition(async () => {
      const response = await fetch("/api/auth/register", {
        method: "POST",
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify(values)
      });

      const payload = (await response.json()) as {error?: string; ok?: boolean};

      if (!response.ok) {
        setErrorMessage(payload.error ?? "Unable to create account.");
        return;
      }

      await signIn("credentials", {
        email: values.email,
        password: values.password,
        redirect: false
      });

      setMessage("Account created successfully.");
      router.push(`/${locale}` as Route);
      router.refresh();
    });
  };

  return (
    <AuthCard
      locale={locale}
      title="Create account"
      description="Customer sign-up automatically joins the selected demo tenant or the first public tenant."
      footer={
        <div className="text-sm">
          <Link className="text-slate-600 hover:text-slate-950" href={`/${locale}${APP_ROUTES.signIn}` as Route}>
            Already have an account?
          </Link>
        </div>
      }
    >
      <form className="space-y-4" onSubmit={form.handleSubmit(onSubmit)}>
        <input type="hidden" {...form.register("preferredLanguage")} />
        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
          <div className="space-y-2">
            <Label htmlFor="firstName">First name</Label>
            <Input id="firstName" {...form.register("firstName")} />
            {form.formState.errors.firstName ? (
              <p className="text-sm text-red-600">{form.formState.errors.firstName.message}</p>
            ) : null}
          </div>
          <div className="space-y-2">
            <Label htmlFor="lastName">Last name</Label>
            <Input id="lastName" {...form.register("lastName")} />
            {form.formState.errors.lastName ? (
              <p className="text-sm text-red-600">{form.formState.errors.lastName.message}</p>
            ) : null}
          </div>
        </div>
        <div className="space-y-2">
          <Label htmlFor="tenantSlug">Tenant slug</Label>
          <Input id="tenantSlug" placeholder="swift-drive" {...form.register("tenantSlug")} />
        </div>
        <div className="space-y-2">
          <Label htmlFor="email">Email</Label>
          <Input id="email" type="email" {...form.register("email")} />
          {form.formState.errors.email ? (
            <p className="text-sm text-red-600">{form.formState.errors.email.message}</p>
          ) : null}
        </div>
        <div className="space-y-2">
          <Label htmlFor="password">Password</Label>
          <Input id="password" type="password" {...form.register("password")} />
          {form.formState.errors.password ? (
            <p className="text-sm text-red-600">{form.formState.errors.password.message}</p>
          ) : null}
        </div>
        <div className="space-y-2">
          <Label htmlFor="confirmPassword">Confirm password</Label>
          <Input id="confirmPassword" type="password" {...form.register("confirmPassword")} />
          {form.formState.errors.confirmPassword ? (
            <p className="text-sm text-red-600">{form.formState.errors.confirmPassword.message}</p>
          ) : null}
        </div>
        {message ? <Alert className="border-emerald-200 bg-emerald-50 text-emerald-700">{message}</Alert> : null}
        {errorMessage ? <Alert className="border-red-200 bg-red-50 text-red-700">{errorMessage}</Alert> : null}
        <Button className="w-full" disabled={isPending} size="lg" type="submit">
          {isPending ? "Creating account..." : "Create account"}
        </Button>
      </form>
    </AuthCard>
  );
}