import {
	SET_SITES,
	SET_RECENT_SITES,
	SET_SITES_TOTAL_ITEMS,
	SET_SITES_BY_LANG,
	SET_CURRENT_SITE_INFO,
	SET_CURRENT_SITE_PAGES,
	SET_ALL_SITE_PAGES,
	SET_FILTER,
	SET_TOTAL_ITEMS,
	SET_CURRENT_SITE_LANGUAGES,
	SET_INITIAL_VALUES,
	SET_SAVED_SITE_INFO,
	SET_CURRENT_SITE_ERROR_PAGES,
	SET_CONTENT_FILTERS,
	SET_CONFIG,
	SET_CURRENT_SEARCH,
	SET_THEME_ELEMENTS,
	SET_IS_SITES_LOADING,
	SET_ALL_SITES,
} from "./constants";

import type { ISite, IPage, ILanguage, ISiteListConfig, IQueryValue, IThemeElements } from "@ax/types";

import { SitesActionsCreators } from "./interfaces";

export interface ISitesState {
	currentSiteName: string | null;
	currentSitePages: IPage[];
	allSitePages: IPage[];
	sites: ISite[];
	recentSites: ISite[];
	sitesTotalItems: number;
	allSites: ISite[];
	sitesByLang: ISite[];
	currentSiteInfo: ISite | null;
	currentFilter: string | null;
	totalItems: number;
	currentSiteLanguages: ILanguage[];
	savedSiteInfo: any;
	currentSiteErrorPages: number[];
	contentFilters: Record<string, IQueryValue[]> | null;
	config: ISiteListConfig;
	currentSearch: string;
	themeElements: IThemeElements | null;
	isSitesLoading: boolean;
}

const config: ISiteListConfig = {
	displayRecentSites: false,
	mode: "grid",
	filter: "&order=lastAccess-desc",
	filterValues: {
		order: [{ value: "lastAccess-desc", label: "lastAccess-desc" }],
		liveStatus: [{ value: "all", label: "All" }],
	},
	sortedListStatus: {
		isAscending: false,
		sortedByDateCreated: false,
		sortedByLastAccess: true,
		sortedByTitle: false,
	},
};

export const initialState = {
	currentSiteName: null,
	currentSitePages: [],
	allSitePages: [],
	sites: [],
	allSites: [],
	recentSites: [],
	sitesByLang: [],
	currentSiteInfo: null,
	currentFilter: "unique-pages",
	totalItems: 0,
	sitesTotalItems: 0,
	currentSiteLanguages: [],
	savedSiteInfo: null,
	currentSiteErrorPages: [],
	contentFilters: null,
	config,
	currentSearch: "",
	themeElements: null,
	isSitesLoading: false,
};

export function reducer(state = initialState, action: any): ISitesState {
	switch (action.type) {
		case SET_FILTER:
		case SET_SITES:
		case SET_RECENT_SITES:
		case SET_SITES_TOTAL_ITEMS:
		case SET_SITES_BY_LANG:
		case SET_CURRENT_SITE_INFO:
		case SET_CURRENT_SITE_PAGES:
		case SET_ALL_SITE_PAGES:
		case SET_TOTAL_ITEMS:
		case SET_CURRENT_SITE_LANGUAGES:
		case SET_INITIAL_VALUES:
		case SET_SAVED_SITE_INFO:
		case SET_CURRENT_SITE_ERROR_PAGES:
		case SET_CONTENT_FILTERS:
		case SET_CONFIG:
		case SET_CURRENT_SEARCH:
		case SET_THEME_ELEMENTS:
		case SET_IS_SITES_LOADING:
		case SET_ALL_SITES:
			return { ...state, ...action.payload };
		default:
			return state;
	}
}

export { initialState as sitesInitialState, reducer as sitesReducer };
