import type { ILanguage } from "@ax/types";

import { REHYDRATE } from "redux-persist/lib/constants";

import {
	IS_LOGGING_IN,
	LOGOUT,
	RESET_LOADING,
	SET_ERROR,
	SET_GLOBAL_LANGUAGES,
	SET_GLOBAL_SETTINGS,
	SET_HAS_ANIMATION,
	SET_IS_LOADING,
	SET_IS_SAVING,
	SET_LANGUAGE,
	SET_SESSION_STARTED_AT,
	SET_TOKEN,
	SET_USER,
} from "./constants";

export interface IAppState {
	isRehydrated: boolean;
	isLoading: boolean;
	loadingCount: number;
	isSaving: boolean;
	error: IError;
	user: IUser;
	token: string;
	isLoggingIn: boolean;
	lang: { locale: string; id: number };
	globalLangs: ILanguage[];
	globalSettings: IGlobalSettings;
	sessionStartedAt: null | Date;
	hasAnimation: boolean;
	schemasLoading: boolean;
	schemasError: string | null;
}
export interface IError {
	code?: number;
	text: string;
	btnText?: string | undefined;
	actionsBelow?: boolean | undefined;
	subErrors?: any[];
	btnAction?: () => void;
}

export interface IUser {
	email: string;
}

export interface IGlobalSettings {
	cloudinaryName: string | null;
	globalLogoBig: string;
	globalLogoMini: string;
	siteLogoBig: string;
	siteLogoMini: string;
	welcomeText1: string;
	welcomeText2: string;
	skipReviewOnPublish?: boolean;
	autoSummary: boolean;
	autoTranslation: boolean;
	SSOActivated: boolean;
	SSOWelcomeText: string;
	useForms: boolean;
}

export const initialState = {
	isRehydrated: true,
	isLoading: true,
	loadingCount: 0,
	isSaving: false,
	error: {
		code: undefined,
		text: "",
	},
	user: {
		email: "",
	},
	token: "",
	isLoggingIn: false,
	lang: {
		locale: "en-GB",
		id: 4,
	},
	globalLangs: [],
	globalSettings: {
		cloudinaryName: "",
		globalLogoBig: "",
		globalLogoMini: "",
		siteLogoBig: "",
		siteLogoMini: "",
		welcomeText1: "",
		welcomeText2: "",
		autoSummary: false,
		autoTranslation: false,
		SSOActivated: false,
		SSOWelcomeText: "",
		useForms: false,
	},
	sessionStartedAt: null,
	hasAnimation: false,
	schemasLoading: false,
	schemasError: null,
};

export function reducer(state = initialState, action: any): IAppState {
	switch (action.type) {
		case REHYDRATE:
			return { ...state, isRehydrated: true, loadingCount: 0, schemasLoading: false, schemasError: null };
		case SET_IS_LOADING: {
			const delta = action.payload.isLoading ? 1 : -1;
			const loadingCount = Math.max(0, state.loadingCount + delta);
			return { ...state, loadingCount, isLoading: loadingCount > 0 };
		}
		case RESET_LOADING:
			return { ...state, loadingCount: 0, isLoading: true };
		case SET_TOKEN:
		case SET_IS_SAVING:
		case IS_LOGGING_IN:
		case LOGOUT:
		case SET_LANGUAGE:
		case SET_GLOBAL_LANGUAGES:
		case SET_GLOBAL_SETTINGS:
		case SET_USER:
		case SET_SESSION_STARTED_AT:
		case SET_HAS_ANIMATION:
			return { ...state, ...action.payload };
		case SET_ERROR:
			return { ...state, error: { ...action.payload } };
		default:
			return state;
	}
}

export { initialState as appInitialState, reducer as appReducer };
