"use client";

import { useState } from "react";
import Link from "next/link";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { Mail, ArrowLeft, MailCheck } from "lucide-react";
import { toast } from "sonner";
import { useTranslation } from "@/lib/hooks/use-translation";
import { zMsg } from "@/lib/utils/translated-zod";
import { authApi } from "@/lib/api/client";

const schema = z.object({
  email: z.string().email(zMsg("auth.email_invalid", "Please enter a valid email")),
});
type Values = z.infer<typeof schema>;

export default function ForgotPasswordPage() {
  const [sent, setSent] = useState(false);
  const [loading, setLoading] = useState(false);
  const { t: cms } = useTranslation("LOGIN");

  const form = useForm<Values>({ resolver: zodResolver(schema) });

  async function onSubmit(values: Values) {
    try {
      setLoading(true);
      await authApi.forgotPassword({ email: values.email });
      // Shown whatever the server found. It answers 200 either way by design,
      // so a screen that said "sent!" only for real accounts would leak exactly
      // what the endpoint is built not to reveal.
      setSent(true);
    } catch (err: unknown) {
      const msg =
        (err as { response?: { data?: { message?: string } } })?.response?.data?.message ??
        "Could not send the reset link";
      toast.error(msg);
    } finally {
      setLoading(false);
    }
  }

  const inputCls =
    "w-full rounded-md border border-gray-300 px-3 py-2 text-sm shadow-sm placeholder:text-gray-400 focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500";
  const btnPrimary =
    "w-full rounded-md bg-indigo-600 px-4 py-2.5 text-sm font-semibold text-white shadow hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed transition";

  return (
    <div className="min-h-screen flex items-center justify-center bg-gray-100 px-4 py-12">
      <div className="w-full max-w-md bg-white rounded-xl shadow-lg p-8">
        <h1 className="text-xl font-bold text-center text-gray-900 mb-1">
          {cms("forgot.title", "पासवर्ड रीसेट करें / Reset your password")}
        </h1>

        {!sent ? (
          <>
            <p className="text-sm text-center text-gray-500 mb-6">
              {cms(
                "forgot.subtitle",
                "अपना पंजीकृत ईमेल दर्ज करें — हम एक लिंक भेजेंगे / Enter your registered email and we will send you a link"
              )}
            </p>

            <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  <Mail className="inline h-4 w-4 mr-1" />
                  {cms("auth_labels.email_label", "ईमेल / Email")}
                </label>
                <input
                  type="email"
                  className={inputCls}
                  placeholder="you@example.com"
                  autoFocus
                  {...form.register("email")}
                />
                {form.formState.errors.email && (
                  <p className="text-xs text-red-500 mt-1">
                    {form.formState.errors.email.message}
                  </p>
                )}
              </div>

              <button type="submit" disabled={loading} className={btnPrimary}>
                {loading
                  ? cms("auth_labels.loading_text", "कृपया प्रतीक्षा करें...")
                  : cms("forgot.submit", "लिंक भेजें / Send link")}
              </button>
            </form>
          </>
        ) : (
          <div className="text-center py-4">
            <MailCheck className="h-12 w-12 text-green-600 mx-auto mb-4" />
            <p className="text-sm text-gray-700 mb-2">
              {cms(
                "forgot.sent_hi",
                "यदि उस पते पर खाता है, तो रीसेट लिंक भेज दिया गया है।"
              )}
            </p>
            <p className="text-sm text-gray-500 mb-4">
              {cms(
                "forgot.sent_en",
                "If that address has an account, a reset link is on its way."
              )}
            </p>
            <p className="text-xs text-gray-400">
              {cms(
                "forgot.check_spam",
                "कुछ मिनट लग सकते हैं — स्पैम फ़ोल्डर भी देखें। / It may take a few minutes — check your spam folder too."
              )}
            </p>
          </div>
        )}

        <Link
          href="/auth"
          className="mt-6 flex items-center justify-center gap-1 text-sm text-indigo-600 hover:underline"
        >
          <ArrowLeft className="h-4 w-4" />
          {cms("forgot.back_to_login", "लॉगिन पर वापस जाएं / Back to login")}
        </Link>
      </div>
    </div>
  );
}
