import { useTranslate } from "@/utils/i18n";

import SettingGroup from "./SettingGroup";
import SettingSection from "./SettingSection";
import AccessTokenSection from "./AccessTokenSection";
import LocaleSelect from "../LocaleSelect";
import ThemeSelect from "../ThemeSelect";
import { UserSetting_GeneralSetting, UserSetting_GeneralSettingSchema } from "@/types/proto/api/v1/user_service_pb";
import { useAuth } from "@/contexts/AuthContext";
import { create } from "@bufbuild/protobuf";
import { useUpdateUserGeneralSetting } from "@/hooks/useUserQueries";
import { loadLocale } from "@/utils/i18n";
import { loadTheme } from "@/utils/theme";
import SettingRow from "./SettingRow";

const MyAccountSection = () => {
  const t = useTranslate();

  const { currentUser, userGeneralSetting: generalSetting, refetchSettings } = useAuth();
  const { mutate: updateUserGeneralSetting } = useUpdateUserGeneralSetting(currentUser?.name);

  const handleLocaleSelectChange = async (locale: Locale) => {
    loadLocale(locale);
    updateUserGeneralSetting(
      { generalSetting: { locale }, updateMask: ["locale"] },
      { onSuccess: () => refetchSettings() },
    );
  };

  const handleThemeChange = async (theme: string) => {
    loadTheme(theme);
    updateUserGeneralSetting(
      { generalSetting: { theme }, updateMask: ["theme"] },
      { onSuccess: () => refetchSettings() },
    );
  };

  const setting: UserSetting_GeneralSetting =
    generalSetting ||
    create(UserSetting_GeneralSettingSchema, {
      locale: "en",
      memoVisibility: "PRIVATE",
      theme: "system",
    });

  return (
    <SettingSection>
      {/* General Settings */}      <SettingGroup title={t("setting.preference")} showSeparator>
        <SettingRow label={t("common.language")}>
          <LocaleSelect value={setting.locale} onChange={handleLocaleSelectChange} />
        </SettingRow>

        <SettingRow label={t("setting.preference-section.theme")}>
          <ThemeSelect value={setting.theme} onValueChange={handleThemeChange} />
        </SettingRow>
      </SettingGroup>

      <SettingGroup title={t("setting.access-token")} showSeparator>
        <AccessTokenSection />
      </SettingGroup>
    </SettingSection>
  );
};

export default MyAccountSection;
