"use client";

import { useState } from "react";
import Link from "next/link";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { forgotPasswordSchema } from "@/lib/validation/schemas";
import { createClient } from "@/lib/supabase/client";
import { AuthLayout } from "@/components/layout/auth-layout";
import { Input, Label, FieldError } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { useTranslations } from "@/lib/i18n/i18n-provider";

export default function ForgotPasswordPage({ params }: { params: { locale: string } }) {
  const t = useTranslations();
  const [sent, setSent] = useState(false);
  const {
    register,
    handleSubmit,
    formState: { errors, isSubmitting }
  } = useForm<{ email: string }>({ resolver: zodResolver(forgotPasswordSchema) });

  async function onSubmit(values: { email: string }) {
    const supabase = createClient();
    await supabase.auth.resetPasswordForEmail(values.email, {
      redirectTo: `${window.location.origin}/${params.locale}/reset-password`
    });
    // Always show the same message whether or not the account exists, to
    // avoid leaking which emails are registered.
    setSent(true);
  }

  return (
    <AuthLayout
      locale={params.locale}
      title={t("auth.forgotPassword.title")}
      subtitle={t("auth.forgotPassword.subtitle")}
    >
      {sent ? (
        <p className="text-sm text-ink-600">{t("auth.forgotPassword.sent")}</p>
      ) : (
        <form onSubmit={handleSubmit(onSubmit)} noValidate className="space-y-4">
          <div>
            <Label htmlFor="email">{t("auth.forgotPassword.email")}</Label>
            <Input id="email" type="email" error={errors.email?.message} {...register("email")} />
            <FieldError id="email-error">{errors.email?.message}</FieldError>
          </div>
          <Button type="submit" className="w-full" loading={isSubmitting}>
            {t("auth.forgotPassword.submit")}
          </Button>
        </form>
      )}
      <p className="mt-6 text-center text-sm text-ink-500">
        <Link href={`/${params.locale}/login`} className="font-medium text-brand-600 hover:underline">
          {t("common.back")}
        </Link>
      </p>
    </AuthLayout>
  );
}
