import { useEffect, useState } from "react";

import { selects } from "@ax/api";
import { CheckGroupFilter } from "@ax/components";
import { isReqOk } from "@ax/helpers";
import type { IFilterValue, IQueryValue } from "@ax/types";

const SiteFilter = (props: ISiteFilterProps): JSX.Element => {
	const {
		filterItems,
		value,
		pointer,
		label = "Site",
		addGlobal = false,
		filters = [
			{
				name: "all",
				value: "all",
				title: "All",
			},
		],
	} = props;

	const [options, setOptions] = useState(filters);

	if (addGlobal) {
		filters.push({
			name: "global",
			value: "global",
			title: "Global",
		});
	}

	const getSelectSites = async () => {
		try {
			const items = await selects.getSelectSites();
			if (items && isReqOk(items.status)) {
				return items.data;
			}
		} catch (e) {
			console.log(e);
		}
		return false;
	};

	// biome-ignore lint/correctness/useExhaustiveDependencies: TODO: fix this
	useEffect(() => {
		getSelectSites()
			.then((items) => {
				items?.forEach((item: { value: string; label: string }) => {
					const newFilter = {
						name: item.value,
						value: item.value,
						title: item.label,
					};
					filters.push(newFilter);
				});

				setOptions(filters);
			})
			.catch((apiError) => console.log(apiError));
	}, []);

	return (
		<CheckGroupFilter
			filterItems={filterItems}
			value={value[pointer]}
			pointer={pointer}
			label={label}
			description="Filter by Site"
			initialState={["all"]}
			selectAllOption="all"
			filters={options}
			menuPosition="left"
			multipleSelection={true}
			search={true}
		/>
	);
};

export interface ISiteFilterProps {
	filterItems(pointer: string, filter: IQueryValue[]): void;
	value: Record<string, IQueryValue[]>;
	pointer: string;
	center?: boolean;
	label?: string;
	selectAllOption?: string;
	filters?: IFilterValue[];
	addGlobal?: boolean;
}

export default SiteFilter;
