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

import { eventSummary } from "shared/lib/slickgrid";

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

import { useMakeVisible, useSubscribeToEvent } from "../lib";
import { ITotal, SELECTED_ROWS_SUMMARY } from "../model";
import { TotalByColumn } from "./TotalByColumn";

import Styled from "./PopupSummary.style";

export const PopupSummary: FC<Props> = ({ tableId }) => {
	const [rowsNumber, setRowsNumber] = useState(0);
	const [isOpened, setIsOpened] = useState(false);
	const [totals, setTotals] = useState<ITotal>({});

	function onClose() {
		eventSummary.open = false;
	}

	useMakeVisible(isOpened);
	useSubscribeToEvent(setIsOpened, setRowsNumber, setTotals, tableId);

	if (!isOpened) return null;

	return (
		<Fragment>
			<Overlay setIsOpened={setIsOpened} />
			<Popup id={SELECTED_ROWS_SUMMARY}>
				<Styled.Title variant={"h6"}>Selected rows summary</Styled.Title>
				<Styled.RowsNumber>{`Number of selected rows: ${rowsNumber}`}</Styled.RowsNumber>
				<Styled.Ul>
					{Object.entries(totals).map(
						([id, { label, total, totalFormatted }]) => (
							<li key={id}>
								<TotalByColumn
									label={label}
									total={total}
									totalFormatted={totalFormatted}
								/>
							</li>
						),
					)}
				</Styled.Ul>
				<Styled.ButtonContainer>
					<Styled.Button variant={"outlined"} onClick={onClose}>
						Close
					</Styled.Button>
				</Styled.ButtonContainer>
			</Popup>
		</Fragment>
	);
};

interface Props {
	tableId: string;
}
