"use client";

import { useState, useTransition } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { CheckCircle2, Loader2 } from "lucide-react";
import { toast } from "sonner";

import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { FormField } from "@/components/auth/form-field";
import { forgotPasswordAction } from "@/actions/password-actions";
import { forgotPasswordSchema, type ForgotPasswordInput } from "@/validators/auth";
import { useLanguage } from "@/lib/i18n/context";

export function ForgotPasswordForm() {
  const { t, locale } = useLanguage();
  const f = t.auth.form;
  const [isPending, startTransition] = useTransition();
  const [sentMessage, setSentMessage] = useState<string | null>(null);

  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<ForgotPasswordInput>({
    resolver: zodResolver(forgotPasswordSchema),
    defaultValues: { email: "" },
  });

  function onSubmit(values: ForgotPasswordInput) {
    startTransition(async () => {
      const result = await forgotPasswordAction(values, locale);
      if (!result.success) {
        toast.error(result.error);
        return;
      }
      setSentMessage(result.message ?? t.errors.forgotPasswordSuccess);
    });
  }

  if (sentMessage) {
    return (
      <div className="flex flex-col items-center gap-3 py-2 text-center">
        <span className="flex size-12 items-center justify-center rounded-full bg-success/15 text-success">
          <CheckCircle2 className="size-6" />
        </span>
        <p className="text-sm text-muted-foreground">{sentMessage}</p>
      </div>
    );
  }

  return (
    <form onSubmit={handleSubmit(onSubmit)} noValidate className="flex flex-col gap-4">
      <FormField id="email" label={f.email} error={errors.email?.message}>
        <Input
          id="email"
          type="email"
          autoComplete="email"
          aria-invalid={!!errors.email}
          {...register("email")}
        />
      </FormField>

      <Button type="submit" size="lg" disabled={isPending} className="mt-2">
        {isPending ? <Loader2 className="size-4 animate-spin" /> : null}
        {f.sendResetLink}
      </Button>
    </form>
  );
}
