import type {
	IStructuredData,
	IStructuredDataContent,
	IErrorItem,
	IStructuredDataCategory,
	IQueryValue,
} from "@ax/types";
import {
	SET_CATEGORIES,
	SET_STRUCTURED_DATA,
	SET_CURRENT_STRUCTURED_DATA,
	SET_CURRENT_STRUCTURED_DATA_ID,
	SET_CURRENT_STRUCTURED_DATA_CONTENTS,
	SET_SCHEMA,
	CREATE_FORM,
	UPDATE_FORM,
	SET_ENTITY,
	SET_FILTER,
	SET_SCHEMA_VERSION,
	SET_ERRORS,
	SET_VALIDATED,
	SET_CONTENT_FILTERS,
	SET_IS_IA_TRANSLATED,
	SET_CURRENT_DATA_CATEGORY,
	SET_CURRENT_SEARCH,
} from "./constants";

export interface IStructuredDataState {
	isActive: boolean;
	categories: { global: IStructuredData[]; site: IStructuredData[] };
	structuredData: { global: IStructuredData[]; site: IStructuredData[] };
	currentStructuredData: IStructuredData | null;
	currentStructuredDataId: number | null;
	currentDataContent: IStructuredDataContent[];
	currentDataCategory: IStructuredDataCategory[];
	schema: any;
	form: IStructuredDataContent | null;
	entity: string | null;
	currentFilter: string;
	schemaVersion: string;
	errors: IErrorItem[];
	validated: boolean;
	contentFilters: Record<string, Record<string, IQueryValue[]>> | null;
	isIATranslated: boolean;
	currentSearch: string;
}

export const initialState = {
	isActive: false,
	categories: { global: [], site: [] },
	structuredData: { global: [], site: [] },
	currentStructuredData: null,
	currentStructuredDataId: null,
	currentDataContent: [],
	currentDataCategory: [],
	schema: {},
	form: null,
	entity: null,
	currentFilter: "all-pages",
	schemaVersion: "",
	errors: [],
	validated: false,
	contentFilters: null,
	isIATranslated: false,
	currentSearch: "",
};

export function reducer(state = initialState, action: any): IStructuredDataState {
	switch (action.type) {
		case SET_CATEGORIES:
		case SET_STRUCTURED_DATA:
		case SET_CURRENT_STRUCTURED_DATA:
		case SET_CURRENT_STRUCTURED_DATA_ID:
		case SET_CURRENT_STRUCTURED_DATA_CONTENTS:
		case SET_CURRENT_DATA_CATEGORY:
		case SET_SCHEMA:
		case CREATE_FORM:
		case UPDATE_FORM:
		case SET_ENTITY:
		case SET_FILTER:
		case SET_SCHEMA_VERSION:
		case SET_ERRORS:
		case SET_VALIDATED:
		case SET_CONTENT_FILTERS:
		case SET_IS_IA_TRANSLATED:
		case SET_CURRENT_SEARCH:
			return { ...state, ...action.payload };
		default:
			return state;
	}
}

export { initialState as structuredDataInitialState, reducer as structuredDataReducer };
