import { useMemo } from 'react';
import { ColorSchemeName, useColorScheme } from 'react-native';
import { themeStore, themeStoreActions } from '../store';
import { getThemeAssets } from '../utils';
import { useStore } from './useStore';

export type UseThemeArg = {
  themeType?: ColorSchemeName;
};

export function useTheme({ themeType: themeTypeArg }: UseThemeArg = {}) {
  const colorScheme = useColorScheme();
  const { themes, currentThemeType, isNonDefaultThemeType } =
    useStore(themeStore);
  const _themeType = useMemo(() => {
    if (isNonDefaultThemeType) {
      return currentThemeType;
    }
    return colorScheme;
  }, [colorScheme, currentThemeType, isNonDefaultThemeType]);

  return useMemo(
    () => ({
      themeType: _themeType,
      themes,
      themeAssets: getThemeAssets(_themeType),
      theme: themes[themeTypeArg || _themeType],
      setThemeType: themeStoreActions.setThemeTypeAction,
      setThemes: themeStoreActions.setThemesAction,
    }),
    [_themeType, themeTypeArg, themes]
  );
}
