import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { ConfirmOTPResponse } from "pages/otp/types";
import { baseApi } from "redux/api/apiSlice";
import { AppThunk } from "redux/store";
import { ACCESS_TOKEN } from "utils/constants";

export type AuthState = {
  user: any;
  isActivated: boolean;
  loading: boolean;
  loginFailed: boolean;
  expiredToken: boolean;
  error: string;
  token: string;
  loaded: boolean;
};

const initialState: AuthState = {
  user: undefined,
  isActivated: !!localStorage.getItem(ACCESS_TOKEN),
  loaded: false,
  loading: false,
  loginFailed: false,
  expiredToken: false,
  error: "",
  token: localStorage.getItem(ACCESS_TOKEN) || "",
};
export const authSlice = createSlice({
  name: "auth",
  initialState,
  reducers: {
    resetState: () => initialState,
    initialLoadStart(state) {
      state.loading = true;
      state.isActivated = false;
    },
    initialLoadSuccess(state) {
      state.loading = false;
      state.isActivated = true;
    },
    loginStart(state) {
      state.loading = true;
      state.loginFailed = false;
      state.loaded = false;
    },
    loginSuccess(state, action: PayloadAction<ConfirmOTPResponse>) {
      if (action.payload.result.access_token) {
        localStorage.setItem(ACCESS_TOKEN, action.payload.result.access_token);
        state.token = action.payload.result.access_token;
        localStorage.setItem("customer", JSON.stringify(action.payload.result.customer));
      }
    },
    logout: (state) => {
      localStorage.removeItem(ACCESS_TOKEN);
      state.isActivated = false;
      state.token = "";
      state.user = undefined;
    },
    failedWithError(state, action: PayloadAction<string>) {
      state.loading = false;
      state.loginFailed = true;
      state.error = action.payload;
    },
    resetLoadedStatus(state) {
      state.loaded = false;
    },
    setUser(state, action: PayloadAction<any>) {
      state.user = action.payload;
    },
    tokenExpired(state) {
      state.expiredToken = true;
    },
  },
});

export const {
  resetState,
  initialLoadStart,
  initialLoadSuccess,
  loginStart,
  loginSuccess,
  failedWithError,
  tokenExpired,
  logout,
  setUser,
  resetLoadedStatus,
} = authSlice.actions;

export default authSlice.reducer;

export const logoutThunk = (): AppThunk => (dispatch) => {
  if (localStorage.getItem(ACCESS_TOKEN)) {
    localStorage.clear();
    dispatch(baseApi.util.resetApiState());
    dispatch(logout());
  }
};
