import React, { useEffect, useState } from "react";

import { CheckGroupFilter } from "@ax/components";
import { IQueryValue } from "@ax/types";
import { isReqOk } from "@ax/helpers";
import { schemas } from "@ax/api";

const ContentFilter = (props: IContentFilterProps): JSX.Element => {
	const { filterItems, value } = props;

	const filters = [
		{
			name: "all",
			value: "all",
			title: "ALL",
		},
		{
			name: "none",
			value: "none",
			title: "None",
		},
	];

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

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

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

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

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

export interface IContentFilterProps {
	filterItems(pointer: string, filter: IQueryValue[]): void;
	value: IQueryValue[];
}

export default ContentFilter;
