import { FC, Fragment, useState } from "react";

import { EColumnFilter } from "shared/model/enums";
import { IColumnFilterValue } from "shared/model/types";

import { Overlay, Popup } from "entities/popup";

import { useOpenMenu, useSubscribeToEvent } from "../lib";
import { COLUMN_FILTERS, defaultValue } from "../model";
import { ButtonReset } from "./ButtonReset";
import { InputArea } from "./InputArea";
import { SelectFilter } from "./SelectFilter";

import Styled from "./ColumnFilters.style";

export const ColumnFilters: FC<Props> = ({ tableId }) => {
	const [value, setValue] = useState<IColumnFilterValue>(defaultValue);
	const [filterId, setFilterId] = useState<EColumnFilter>(
		EColumnFilter.TextContain,
	);
	const [isOpened, setIsOpened] = useState(false);

	useSubscribeToEvent(setIsOpened, tableId);
	useOpenMenu(isOpened, setFilterId, setValue);

	if (!isOpened) return null;

	return (
		<Fragment>
			<Overlay setIsOpened={setIsOpened} />
			<Popup id={COLUMN_FILTERS}>
				<Styled.Wrapper>
					<SelectFilter filterId={filterId} setFilterId={setFilterId} />
					<InputArea filterId={filterId} setValue={setValue} value={value} />
					<ButtonReset
						setIsOpened={setIsOpened}
						setValue={setValue}
						value={value}
					/>
				</Styled.Wrapper>
			</Popup>
		</Fragment>
	);
};

interface Props {
	tableId: string;
}
