"use client";

import Link from "next/link";
import { signIn } from "next-auth/react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { registerSchema, type RegisterInput } from "@/lib/validation/auth";
import { registerUser } from "@/lib/actions/auth";
import { Button } from "@/components/ui/Button";
import { Input } from "@/components/ui/Input";
import { Field, Label } from "@/components/ui/Card";
import { useState } from "react";

export function RegisterForm() {
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<RegisterInput>({
    resolver: zodResolver(registerSchema),
  });

  async function onSubmit(data: RegisterInput) {
    setLoading(true);
    setError(null);

    const result = await registerUser(data);
    if (!result.success) {
      setError(result.error);
      setLoading(false);
      return;
    }

    const signInResult = await signIn("credentials", {
      email: data.email,
      password: data.password,
      redirect: false,
    });

    setLoading(false);

    if (signInResult?.error) {
      window.location.assign("/login");
      return;
    }

    window.location.assign("/onboarding");
  }

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <Field>
        <Label htmlFor="name">Full name</Label>
        <Input id="name" placeholder="Sachin Kumar" {...register("name")} />
        {errors.name && (
          <p className="mt-1 text-xs text-danger">{errors.name.message}</p>
        )}
      </Field>

      <Field>
        <Label htmlFor="email">Work email</Label>
        <Input
          id="email"
          type="email"
          placeholder="you@company.com"
          {...register("email")}
        />
        {errors.email && (
          <p className="mt-1 text-xs text-danger">{errors.email.message}</p>
        )}
      </Field>

      <Field>
        <Label htmlFor="password">Password</Label>
        <Input
          id="password"
          type="password"
          placeholder="Create a password"
          {...register("password")}
        />
        {errors.password && (
          <p className="mt-1 text-xs text-danger">
            {errors.password.message}
          </p>
        )}
      </Field>

      {error && <p className="mb-3 text-sm text-danger">{error}</p>}

      <Button type="submit" className="w-full" loading={loading}>
        {loading ? "Creating account…" : "Create account →"}
      </Button>

      <p className="mt-3.5 text-center text-[11.5px] text-muted">
        By continuing you agree to our{" "}
        <Link href="#" className="text-primary">
          Terms
        </Link>{" "}
        &{" "}
        <Link href="#" className="text-primary">
          Privacy Policy
        </Link>
        .
      </p>
    </form>
  );
}
