"use client";

import { useAppLanguage } from "@/contexts/LanguageProvider";
import {
  ENABLED_LANGUAGES,
  LANGUAGE_LABELS,
  type AppLanguage,
} from "@/lib/i18n/registry";
import useAxios from "@/hooks/useAxios";
import toast from "react-hot-toast";
import { useTranslation } from "react-i18next";

export default function LanguageSettingRow() {
  const { t } = useTranslation("common");
  const { language, setLanguage } = useAppLanguage();
  const { request } = useAxios();

  const handleChange = async (next: AppLanguage) => {
    if (next === language) return;

    try {
      await setLanguage(next);
      try {
        await request(
          "PATCH",
          "/account/privacy",
          { preferred_language: next },
          { noToast: true }
        );
      } catch {
        // local language still applies when offline / old backend
      }
      toast.success(t("language.saved"));
    } catch {
      toast.error(t("common.saveError"));
    }
  };

  return (
    <div className="rounded-xl border border-neutral-200 px-4 py-3 dark:border-neutral-800">
      <div className="mb-3">
        <p className="font-semibold">{t("language.title")}</p>
        <p className="mt-0.5 text-xs text-neutral-500">
          {t("language.description")}
        </p>
      </div>
      <div className="grid grid-cols-2 gap-2">
        {ENABLED_LANGUAGES.map((code) => {
          const active = language === code;
          return (
            <button
              key={code}
              type="button"
              onClick={() => void handleChange(code)}
              className={`rounded-lg border px-3 py-2 text-sm font-semibold transition-colors ${
                active
                  ? "border-[#0095f6] bg-[#0095f6]/10 text-[#0095f6]"
                  : "border-neutral-200 text-neutral-700 dark:border-neutral-700 dark:text-neutral-200"
              }`}
            >
              {LANGUAGE_LABELS[code].native}
            </button>
          );
        })}
      </div>
    </div>
  );
}
