// src/components/forgot-password-form.tsx
"use client";

import Link from "next/link";
import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import {
  Field,
  FieldDescription,
  FieldGroup,
  FieldLabel,
} from "@/components/ui/field";
import { Input } from "@/components/ui/input";
import { authClient } from "@/lib/auth-client";
import { cn } from "@/lib/utils";

export function ForgotPasswordForm({
  className,
  ...props
}: React.ComponentProps<"div">) {
  const [email, setEmail] = useState("");
  const [pending, setPending] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [sent, setSent] = useState(false);

  async function submit(e: React.FormEvent) {
    e.preventDefault();
    setPending(true);
    setError(null);
    // Absolute callback URL built from the current origin — Better Auth appends
    // ?token=… (or ?error=… on an invalid/expired token) to this URL.
    const res = await authClient.requestPasswordReset({
      email,
      redirectTo: `${window.location.origin}/reset-password`,
    });
    setPending(false);
    if (res.error) {
      setError(res.error.message ?? "Échec de l'envoi du lien.");
    } else {
      // Neutral confirmation regardless of whether the account exists
      // (Better Auth returns a constant response to prevent enumeration).
      setSent(true);
    }
  }

  if (sent) {
    return (
      <div className={cn("flex flex-col gap-6", className)} {...props}>
        <Card>
          <CardContent className="flex flex-col items-center gap-3 p-6 text-center md:p-8">
            <h1 className="font-bold text-2xl">Vérifie ton email</h1>
            <p className="text-balance text-muted-foreground">
              Si un compte existe pour <strong>{email}</strong>, un email avec
              un lien de réinitialisation vient d'être envoyé.
            </p>
            <Link
              href="/login"
              className="text-sm underline underline-offset-4"
            >
              Retour à la connexion
            </Link>
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <div className={cn("flex flex-col gap-6", className)} {...props}>
      <Card>
        <CardContent className="p-6 md:p-8">
          <form onSubmit={submit}>
            <FieldGroup>
              <div className="flex flex-col items-center gap-2 text-center">
                <h1 className="font-bold text-2xl">Mot de passe oublié ?</h1>
                <p className="text-balance text-muted-foreground">
                  Entre ton email pour recevoir un lien de réinitialisation
                </p>
              </div>
              <Field>
                <FieldLabel htmlFor="email">Email</FieldLabel>
                <Input
                  id="email"
                  type="email"
                  placeholder="m@exemple.com"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  required
                />
              </Field>
              {error ? (
                <p className="text-destructive text-sm" role="alert">
                  {error}
                </p>
              ) : null}
              <Field>
                <Button type="submit" disabled={pending || !email}>
                  {pending ? "…" : "Envoyer le lien"}
                </Button>
              </Field>
              <FieldDescription className="text-center">
                Tu te souviens de ton mot de passe ?{" "}
                <Link href="/login">Se connecter</Link>
              </FieldDescription>
            </FieldGroup>
          </form>
        </CardContent>
      </Card>
    </div>
  );
}
