import { useState } from "react";
import { IQueryValue } from "@ax/types";

const useFilterQuery = () => {
	const initialQueryValues: Record<string, IQueryValue[]> = {
		sites: [{ value: "all", label: "All" }],
		users: [{ value: "all", label: "All" }],
		eventTypes: [{ value: "all", label: "All" }],
		contentTypes: [{ value: "all", label: "All" }],
		date: [],
	};

	const [query, setQuery] = useState(initialQueryValues);
	const [currentFilterQuery, setCurrentFilterQuery] = useState<Record<string, string>>({});

	const setFilterQuery = (filterValues: Record<string, IQueryValue[]>) => {
		const filterQuery = Object.fromEntries(
			Object.entries(filterValues)
				.filter(([_, arr]) => Array.isArray(arr) && arr.length > 0 && !(arr.length === 1 && arr[0].value === "all"))
				.map(([key, arr]) => [key, arr.map((item) => item.value).join(",")]),
		);
		setCurrentFilterQuery(filterQuery);
	};

	const setFiltersSelection = (pointer: string, filter: IQueryValue[]) => {
		const { sites, users, eventTypes, contentTypes, date } = query;
		const filterValues: Record<string, IQueryValue[]> = {
			sites: pointer === "sites" ? filter : sites,
			users: pointer === "users" ? filter : users,
			eventTypes: pointer === "eventTypes" ? filter : eventTypes,
			contentTypes: pointer === "contentTypes" ? filter : contentTypes,
			date: pointer === "date" ? filter : date,
		};

		setQuery(filterValues);
		setFilterQuery(filterValues);
	};

	const resetFilterQuery = () => {
		setQuery(initialQueryValues);
		setCurrentFilterQuery({});
	};

	return {
		setFiltersSelection,
		resetFilterQuery,
		filterValues: query,
		filterQuery: currentFilterQuery,
	};
};

export { useFilterQuery };
