import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import dayjs from "dayjs";
import "dayjs/locale/ar";
import LocalizedFormat from "dayjs/plugin/localizedFormat";
import preParsePostFormat from "dayjs/plugin/preParsePostFormat";
import { AppThunk } from "redux/store";
import { DEFAULT_LANGUAGE } from "utils/constants";

dayjs.extend(LocalizedFormat);
dayjs.extend(preParsePostFormat); // for arabic numbers

export type LocaleState = {
  locale: string;
  isRTL: boolean;
};

const initialState: LocaleState = {
  locale:
    localStorage.getItem(DEFAULT_LANGUAGE) ||
    import.meta.env.VITE_DEFAULT_LANGUAGE,
  isRTL:
    (localStorage.getItem(DEFAULT_LANGUAGE) ||
      import.meta.env.VITE_DEFAULT_LANGUAGE) === "ar",
};

function setDateLocale(appLocale: string) {
  switch (appLocale) {
    case "ar":
      dayjs.locale("ar");
      break;
    case "en":
      dayjs.locale("en");
      break;
    default:
      dayjs.locale("en");
      break;
  }
}

export const localeSlice = createSlice({
  name: "locale",
  initialState,
  reducers: {
    setLocale(state, action: PayloadAction<string>) {
      state.locale = action.payload;
      state.isRTL = action.payload === "ar";
    },
  },
});
export const { setLocale } = localeSlice.actions;
export default localeSlice.reducer;

export const setLocalesThunk =
  (newLocale?: string): AppThunk =>
  async (dispatch) => {
    const storedLang = localStorage.getItem(DEFAULT_LANGUAGE);

    const lang =
      newLocale || storedLang || import.meta.env.VITE_DEFAULT_LANGUAGE;
    if (storedLang !== lang) localStorage.setItem(DEFAULT_LANGUAGE, lang);
    setDateLocale(lang);
    dispatch(setLocale(lang));
  };
