"use client";

import Image from "next/image";
import Link from "next/link";
import { useState } from "react";
import { useDashboardI18n } from "@/components/I18nProvider";
import PublicShell from "@/components/layout/PublicShell";
import { resolveApiBase } from "@/lib/api";
import { carplaceUrl } from "@/lib/urls";

const DASHBOARD_LOGO_SRC = "/dashboard/rentaldrivego.png";

export default function ForgotPasswordPageClient({
  embedded = false,
}: {
  embedded?: boolean;
}) {
  const { language } = useDashboardI18n();
  const dict = {
    en: {
      title: "Forgot your password?",
      subtitle: "Enter your work email and we'll send you a reset link.",
      email: "Email",
      emailPlaceholder: "owner@company.com",
      submit: "Send reset link",
      submitting: "Sending…",
      backToLogin: "Back to sign in",
      successTitle: "Check your email",
      successBody:
        "If that email is registered, a reset link has been sent. It expires in 60 minutes.",
      error: "Something went wrong. Please try again.",
    },
    fr: {
      title: "Mot de passe oublié ?",
      subtitle:
        "Entrez votre email professionnel et nous vous enverrons un lien de réinitialisation.",
      email: "Email",
      emailPlaceholder: "owner@company.com",
      submit: "Envoyer le lien",
      submitting: "Envoi…",
      backToLogin: "Retour à la connexion",
      successTitle: "Vérifiez votre email",
      successBody:
        "Si cet email est enregistré, un lien de réinitialisation a été envoyé. Il expire dans 60 minutes.",
      error: "Une erreur est survenue. Veuillez réessayer.",
    },
    ar: {
      title: "نسيت كلمة المرور؟",
      subtitle: "أدخل بريدك الإلكتروني وسنرسل لك رابط إعادة التعيين.",
      email: "البريد الإلكتروني",
      emailPlaceholder: "owner@company.com",
      submit: "إرسال رابط إعادة التعيين",
      submitting: "جارٍ الإرسال…",
      backToLogin: "العودة إلى تسجيل الدخول",
      successTitle: "تحقق من بريدك الإلكتروني",
      successBody:
        "إذا كان البريد الإلكتروني مسجلاً، فقد تم إرسال رابط إعادة التعيين. تنتهي صلاحيته خلال 60 دقيقة.",
      error: "حدث خطأ ما. يرجى المحاولة مرة أخرى.",
    },
  }[language];

  const [email, setEmail] = useState("");
  const [loading, setLoading] = useState(false);
  const [sent, setSent] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setLoading(true);
    setError(null);
    try {
      const apiBase = resolveApiBase();
      // Try employee first, then admin — mirrors the sign-in page which handles both
      const [empRes, adminRes] = await Promise.all([
        fetch(`${apiBase}/auth/employee/forgot-password`, {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ email }),
        }),
        fetch(`${apiBase}/admin/auth/forgot-password`, {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ email }),
        }),
      ]);
      if (!empRes.ok && !adminRes.ok) throw new Error();
      setSent(true);
    } catch {
      setError(dict.error);
    } finally {
      setLoading(false);
    }
  }

  return (
    <PublicShell embedded={embedded} hideFooter hideHeaderActions>
      <main className="flex flex-1 items-center justify-center px-4 py-12">
        <div className="w-full max-w-md">
          <div className="mb-8 text-center">
            <div className="flex justify-center">
              <a href={carplaceUrl} target="_top">
                <Image
                  src={DASHBOARD_LOGO_SRC}
                  alt="RentalDriveGo"
                  width={104}
                  height={104}
                  unoptimized
                  className="h-24 w-24 rounded-[1.75rem] border border-stone-200 bg-white p-1.5 shadow-sm transition-colors dark:border-blue-800 dark:bg-blue-950"
                />
              </a>
            </div>
            <h1 className="mt-4 text-3xl font-black tracking-tight text-stone-900 dark:text-stone-100">
              {dict.title}
            </h1>
            <p className="mt-2 text-sm text-stone-500 dark:text-stone-400">
              {dict.subtitle}
            </p>
          </div>

          <section className="rounded-[2rem] border border-stone-200 bg-white p-8 shadow-sm transition-colors dark:border-blue-900 dark:bg-blue-950">
            {sent ? (
              <div className="space-y-4 text-center">
                <div className="mx-auto flex h-14 w-14 items-center justify-center rounded-full bg-emerald-100 dark:bg-emerald-950/50">
                  <svg
                    className="h-7 w-7 text-emerald-600 dark:text-emerald-400"
                    fill="none"
                    viewBox="0 0 24 24"
                    stroke="currentColor"
                    strokeWidth={2}
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      d="M5 13l4 4L19 7"
                    />
                  </svg>
                </div>
                <h2 className="text-xl font-bold text-stone-900 dark:text-stone-100">
                  {dict.successTitle}
                </h2>
                <p className="text-sm text-stone-500 dark:text-stone-400">
                  {dict.successBody}
                </p>
              </div>
            ) : (
              <form onSubmit={handleSubmit} className="space-y-5">
                {error && (
                  <div className="rounded-2xl border border-rose-200 bg-rose-50 px-4 py-3 text-sm text-rose-700 dark:border-rose-800 dark:bg-rose-950/40 dark:text-rose-400">
                    {error}
                  </div>
                )}
                <div>
                  <label className="mb-1.5 block text-sm font-medium text-stone-700 dark:text-stone-300">
                    {dict.email}
                  </label>
                  <input
                    type="email"
                    required
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                    placeholder={dict.emailPlaceholder}
                    className="input-field"
                  />
                </div>
                <button
                  type="submit"
                  disabled={loading}
                  className="btn-primary w-full justify-center disabled:cursor-not-allowed disabled:opacity-60"
                >
                  {loading ? dict.submitting : dict.submit}
                </button>
              </form>
            )}

            <div className="mt-6 border-t border-stone-200 pt-6 text-center text-sm text-stone-500 dark:border-blue-900 dark:text-stone-400">
              <Link
                href="/sign-in"
                className="font-semibold text-stone-900 underline decoration-stone-300 underline-offset-4 dark:text-stone-100 dark:decoration-stone-700"
              >
                {dict.backToLogin}
              </Link>
            </div>
          </section>
        </div>
      </main>
    </PublicShell>
  );
}
