import { makeAutoObservable } from "mobx";
import { NativeModules, StatusBarStyle } from "react-native";
import { MMKV } from "react-native-mmkv";
import { Dimensions_Window, Platform_Android } from "./commons";
import { ModalPortal } from "./components";
import { AndroidInputModeType, DimensionsType } from "./types";

const { LocaleModule, InputModeModule } = NativeModules;
const { width, height } = Dimensions_Window;

const MMKVStorage = new MMKV();

class TBaseStore {
  statusBar: StatusBarStyle = "dark-content";
  inputType: AndroidInputModeType = "resize";
  inputCurrent: AndroidInputModeType = "resize";

  dimens: DimensionsType = {
    width,
    height,
    cached: 0,
    keyboard: 0,
    duration: 250,
  };

  totalModal = 0;

  constructor() {
    this.dimens = {
      ...this.dimens,
      cached: MMKVStorage.getNumber("keyboard") || 250,
    };
    makeAutoObservable(this);
  }

  private update(key: keyof this, value: any) {
    this[key] = value;
  }

  updateDimens = (value: any) => {
    this.dimens = { ...this.dimens, ...value };
  };

  updateKeyboard = (value: any, duration?: number) => {
    if (typeof value !== "number" || value === this.dimens.keyboard) return;
    const cached = value > 0 ? value : this.dimens.cached;
    this.dimens = {
      ...this.dimens,
      cached,
      keyboard: value,
      duration: duration || this.dimens.duration,
    };
    MMKVStorage.set("keyboard", cached);
  };

  setStatusBar = (statusBar: StatusBarStyle) => {
    this.update("statusBar", statusBar);
  };

  setAndroidInputMode = (type: AndroidInputModeType, withCache?: boolean) => {
    if (!Platform_Android) return;
    withCache && this.update("inputType", type);
    if (type !== this.inputCurrent) {
      InputModeModule.set(type);
      this.update("inputCurrent", type);
    }
  };

  setAndroidLocale = (lang: string) => {
    if (!Platform_Android) return;
    LocaleModule.set(lang);
  };

  setTotalModal = (total: number) => {
    this.update("totalModal", total);
  };

  hideAllModal = () => {
    ModalPortal.dismissAll();
  };
}

export const tBaseStore = new TBaseStore();
