/* eslint-disable react-hooks/exhaustive-deps */
import { useLayoutEffect } from 'react';

import useLocalStorageState from 'use-local-storage-state';
import { DEFAULT_BACKGROUND_COLOR } from '@/shared/constants/colors';
import { StorageKeys } from '@/shared/constants/local-storage';
import { NativeFunction } from '@/shared/constants/native-function';
import { useRouterListener } from './use-router-listener';

export const useChangeBgColor = (color: string) => {
  const [, setAppColor] = useAppColor();

  useLayoutEffect(() => {
    setAppColor(color);
    window.webViewBridge.send(NativeFunction.SetAppColor, color);
    document.body.style.backgroundColor = color;
  }, []);
};

export const useResetBgColor = () => {
  const [, setAppColor] = useAppColor();
  const defaultColor = DEFAULT_BACKGROUND_COLOR;

  useLayoutEffect(() => {
    setAppColor(defaultColor);
    window.webViewBridge.send(NativeFunction.SetAppColor, defaultColor);
    document.body.style.backgroundColor = defaultColor;
  }, []);
};

export const useResetBgColorOnLeave = () => {
  const [, setAppColor] = useAppColor();
  const defaultColor = DEFAULT_BACKGROUND_COLOR;

  useRouterListener(() => {
    setAppColor(defaultColor);
    document.body.style.backgroundColor = defaultColor;
    window.webViewBridge.send(NativeFunction.SetAppColor, defaultColor);
  });
};

export const useAppColor = () => {
  return useLocalStorageState(StorageKeys.AppColor, { defaultValue: DEFAULT_BACKGROUND_COLOR });
};
