"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { api } from "@/lib/client";
import { useT } from "@/components/providers";

/** Presentation preferences — persisted server-side with the account, applied everywhere. */
export function PrefsCard({ initialLocale, initialTheme }: { initialLocale: "ar" | "en" | null; initialTheme: "light" | "dark" | null }) {
  const { t } = useT();
  const router = useRouter();
  const [locale, setLocale] = useState(initialLocale ?? "");
  const [theme, setTheme] = useState(initialTheme ?? "");
  const [saved, setSaved] = useState(false);
  const [busy, setBusy] = useState(false);

  // mounted without server-side initials → hydrate from the signed-in user's saved prefs
  useEffect(() => {
    if (initialLocale === null && initialTheme === null) {
      void api<{ user: { preferences: { locale: "ar" | "en" | null; theme: "light" | "dark" | null } } }>("/api/auth/me").then((res) => {
        if (res.status === 200 && res.data?.user) {
          setLocale(res.data.user.preferences.locale ?? "");
          setTheme(res.data.user.preferences.theme ?? "");
        }
      });
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  async function persist(next: { locale?: string; theme?: string }) {
    setBusy(true);
    setSaved(false);
    const res = await api("/api/auth/preferences", "PUT", next);
    setBusy(false);
    if (res.status === 200) {
      setSaved(true);
      if (next.theme) {
        const dark = next.theme === "dark";
        document.documentElement.classList.toggle("dark", dark);
        localStorage.setItem("bousla_theme", next.theme);
        document.cookie = `bousla_theme=${next.theme}; path=/; max-age=31536000; samesite=strict`;
      }
      if (next.locale) {
        document.cookie = `bousla_locale=${next.locale}; path=/; max-age=31536000; samesite=strict`;
      }
      router.refresh();
    }
  }

  return (
    <section className="rounded-xl border border-slate-200 bg-white p-6 shadow-card">
      <h2 className="font-bold text-slate-900">{t.prefs.title}</h2>
      <p className="mt-1 text-xs text-slate-400">{t.prefs.subtitle}</p>
      <div className="mt-4 grid gap-4 sm:grid-cols-2">
        <div>
          <label htmlFor="pref-locale" className="mb-1 block text-xs font-bold text-slate-600">{t.prefs.language}</label>
          <select
            id="pref-locale"
            value={locale}
            disabled={busy}
            onChange={(e) => { setLocale(e.target.value); void persist({ locale: e.target.value }); }}
            className="w-full rounded-lg border border-slate-300 bg-white px-3 py-2 text-sm outline-none focus:border-bousla-500 focus:ring-2 focus:ring-bousla-100"
          >
            <option value="ar">{t.prefs.arabic}</option>
            <option value="en">{t.prefs.english}</option>
          </select>
        </div>
        <div>
          <label htmlFor="pref-theme" className="mb-1 block text-xs font-bold text-slate-600">{t.prefs.theme}</label>
          <select
            id="pref-theme"
            value={theme}
            disabled={busy}
            onChange={(e) => { setTheme(e.target.value); void persist({ theme: e.target.value }); }}
            className="w-full rounded-lg border border-slate-300 bg-white px-3 py-2 text-sm outline-none focus:border-bousla-500 focus:ring-2 focus:ring-bousla-100"
          >
            <option value="light">{t.prefs.light}</option>
            <option value="dark">{t.prefs.dark}</option>
          </select>
        </div>
      </div>
      {saved && <p role="status" className="mt-3 text-xs font-bold text-emerald-700">{t.prefs.saved}</p>}
    </section>
  );
}
