"use client";

import type {Route} from "next";
import Link from "next/link";
import {useState, useTransition} from "react";
import {zodResolver} from "@hookform/resolvers/zod";
import {useForm} from "react-hook-form";
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 {forgotPasswordSchema} from "@/lib/validations/auth";

type ForgotPasswordFormProps = {
  locale: string;
};

type FormValues = z.infer<typeof forgotPasswordSchema>;

export function ForgotPasswordForm({locale}: ForgotPasswordFormProps) {
  const [isPending, startTransition] = useTransition();
  const [message, setMessage] = useState<string | null>(null);
  const [errorMessage, setErrorMessage] = useState<string | null>(null);
  const form = useForm<FormValues>({
    resolver: zodResolver(forgotPasswordSchema),
    defaultValues: {
      email: ""
    }
  });

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

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

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

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

      setMessage(payload.message ?? "If the account exists, reset instructions were generated.");
      form.reset();
    });
  };

  return (
    <AuthCard
      locale={locale}
      title="Forgot password"
      description="This demo implementation validates the request and records an audit event."
      footer={
        <div className="text-sm">
          <Link className="text-slate-600 hover:text-slate-950" href={`/${locale}${APP_ROUTES.signIn}` as Route}>
            Back to sign in
          </Link>
        </div>
      }
    >
      <form className="space-y-4" onSubmit={form.handleSubmit(onSubmit)}>
        <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>
        {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 ? "Submitting..." : "Request reset"}
        </Button>
      </form>
    </AuthCard>
  );
}