import React, { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { TemplateService } from "@/user-management/services/api/templateService";
import { TemplateSampleSetting } from "@/user-management/services/TemplateConfiguration/types/templateTypes";
import { FONT_RESOURCE_TYPE_ID } from "../utils/templateResourceConstants";
import {
  StyleSettingCard,
  StyleSettingSelect,
} from "./styleSettingsUi";

const EMPTY_FONT_VALUE = "__none__";

export const isFontSetting = (code: string): boolean =>
  code.trim().toLowerCase() === "letter-fonts";

type Props = {
  setting: TemplateSampleSetting;
  isDefault: boolean;
  resourceId: string | null;
  onToggleDefault: (settingId: string) => void;
  onResourceIdChange: (resourceId: string | null) => void;
};

export const FontSettingsEditor: React.FC<Props> = ({
  setting,
  isDefault,
  resourceId,
  onToggleDefault,
  onResourceIdChange,
}) => {
  const { t, i18n } = useTranslation();
  const [fonts, setFonts] = useState<
    Array<{ id: string; name?: { en?: string; am?: string } }>
  >([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    let cancelled = false;
    const loadFonts = async () => {
      setLoading(true);
      try {
        const response = await TemplateService.getTemplates({
          resourceTypeId: FONT_RESOURCE_TYPE_ID,
        });
        if (!cancelled) setFonts(response.items);
      } catch (error) {
        console.error("Failed to load font resources", error);
      } finally {
        if (!cancelled) setLoading(false);
      }
    };
    void loadFonts();
    return () => {
      cancelled = true;
    };
  }, []);

  const locale = i18n.language?.startsWith("am") ? "am" : "en";

  return (
    <StyleSettingCard
      title={t("template.fonts", "Fonts")}
      subtitle={t("template.fontsHint", "Select an optional font resource.")}
      code={setting.code}
      isDefault={isDefault}
      onToggleDefault={() => onToggleDefault(setting.id)}
    >
      <fieldset disabled={isDefault}>
        <StyleSettingSelect
          label={t("template.fontResource", "Font file")}
          value={resourceId ?? EMPTY_FONT_VALUE}
          disabled={loading || isDefault}
          onValueChange={(value) =>
            onResourceIdChange(value === EMPTY_FONT_VALUE ? null : value)
          }
          placeholder={t("template.selectFont", "Select a font")}
          options={[
            {
              value: EMPTY_FONT_VALUE,
              label: t("template.selectFont", "Select a font"),
            },
            ...fonts.map((font) => ({
              value: font.id,
              label: font.name?.[locale] || font.name?.en || font.id,
            })),
          ]}
        />
      </fieldset>
    </StyleSettingCard>
  );
};
