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

import { localStore } from "shared/lib/localStrore";
import { eventHeaderContextMenu } from "shared/lib/slickgrid";

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

import { getHideableColumns, useSubscribeToEvent } from "../lib";
import { HEADER_CONTEXT_MENU } from "../model";
import { ButtonCheckAll } from "./ButtonCheckAll";
import { ButtonUncheckAll } from "./ButtonUncheckAll";
import { Item } from "./Item";
import { Title } from "./Title";

import Styled from "./HeaderContextMenu.style";

export const HeaderContextMenu: FC<Props> = ({ tableId }) => {
	const [hidden, setHidden] = useState<string[]>(
		localStore.hiddenColumns.get(tableId),
	);
	const [isOpened, setIsOpened] = useState(false);

	useSubscribeToEvent(setIsOpened, tableId);

	useEffect(() => {
		if (!isOpened) return;
		const table = eventHeaderContextMenu.table;
		if (!table?.columnPicker) return;
		setHidden([...table.columnPicker.hiddenColumnIds]);
	}, [isOpened]);

	if (!isOpened) return null;
	const table = eventHeaderContextMenu.table;
	if (!table?.columnPicker) return null;

	return (
		<Fragment>
			<Overlay setIsOpened={setIsOpened} />
			<Popup id={HEADER_CONTEXT_MENU}>
				<Title />
				<Styled.ItemsGroup>
					{getHideableColumns(table).map(({ id, name }) => (
						<Fragment key={id}>
							<Item
								columnId={id as string}
								columnName={name as string}
								hidden={hidden}
								setHidden={setHidden}
							/>
						</Fragment>
					))}
				</Styled.ItemsGroup>
				<Styled.ButtonsGroup className={"header-context-menu-footer"}>
					<ButtonCheckAll setHidden={setHidden} />
					<ButtonUncheckAll setHidden={setHidden} />
				</Styled.ButtonsGroup>
			</Popup>
		</Fragment>
	);
};

interface Props {
	tableId: string;
}
