import { useMemo } from 'react';
import useSWRImmutable from 'swr/immutable';
import { fetchSettings } from '@features/block-editor/api';
import type { EditorSettings, EditorSettingsOverride, FeaturesSetting } from '@features/block-editor/types';
import { settingCacheKey } from '@features/block-editor/lib/utils/settingCacheKey';
import mergeSettings from '@features/block-editor/utils/mergeSettings';

async function fetcher() {
  const data = await fetchSettings();
  return data;
}

const defaultFeatures: FeaturesSetting = {
  textItalic: false,
  textUnderline: false,
  textStrike: false,
  textCode: false,
  textMarker: false,
  textColor: false,
  fontSize: false,
  fontFamily: false,
  textSubscript: false,
  textSuperscript: false,
  customClass: false,
  tableBgColor: false,
  imageDefaultLightbox: true,
};

export function useSettings(override?: EditorSettingsOverride): EditorSettings {
  const { data } = useSWRImmutable<EditorSettings>(settingCacheKey, fetcher);

  return useMemo<EditorSettings>(() => {
    const base: EditorSettings = {
      features: data?.features || defaultFeatures,
      blockMenus: data?.blockMenus || [],
      fontSize: data?.fontSize || [],
      fontFamily: data?.fontFamily || [],
      customClass: data?.customClass || [],
      imageSizes: data?.imageSizes || [],
      colorPalette: data?.colorPalette || [],
    };
    return mergeSettings(base, override);
  }, [data, override]);
}
