import { useEffect, useState } from "react";

import { Button, CheckField, ExportButton, Loader } from "@ax/components";
import type { ItemLabel } from "@ax/constants";
import type { IBulkSelectedItems } from "@ax/hooks";
import { LOCALE, pluralize } from "@ax/locales";
import type { IBulkAction } from "@ax/types";

import { getBulkLoadingText } from "./utils";

import * as S from "./style";

const BulkSelectionOptions = (props: IBulkSelectionProps) => {
	const {
		isScrolling,
		checkState,
		actions,
		selectItems,
		className,
		exportAction,
		selectedItems,
		isLoading,
		itemLabel = { one: "item", other: "items" },
	} = props;

	const filteredActions = actions.filter((action) => !!action);
	const [currentAction, setCurrentAction] = useState<string>("");

	const currentActionText = getBulkLoadingText(currentAction);
	const allSelectedItemsText = selectedItems?.all.length.toString();
	const itemLabelText = pluralize(itemLabel, selectedItems?.all.length);
	const pleaseWaitText = `${LOCALE.common.pleaseWait}...`;
	const bulkProcessingText = `${currentActionText} ${allSelectedItemsText} ${itemLabelText}. ${pleaseWaitText}`;

	useEffect(() => {
		if (!isLoading) {
			setCurrentAction("");
		}
	}, [isLoading]);

	const handleActionClick = (action: () => void, actionText: string) => {
		setCurrentAction(actionText);
		action();
	};

	return (
		<S.BulkHeader isScrolling={isScrolling} data-testid="bulk-header-wrapper" className={className}>
			{isLoading ? (
				<>
					<Loader name="smallCircle" size="16" />
					<S.LoadingText>{bulkProcessingText}</S.LoadingText>
				</>
			) : (
				<S.BulkActionsWrapper>
					<S.SelectAllCheckField>
						<CheckField
							key="selectAll"
							name="selectAll"
							value="selectAll"
							onChange={selectItems}
							checked={checkState.isAllSelected}
							indeterminate={checkState.indeterminate}
							disabled={isLoading || false}
							error={false}
						/>
					</S.SelectAllCheckField>
					<S.SelectedCount>{selectedItems?.all?.length} selected</S.SelectedCount>
					<S.BulkActions>
						{filteredActions.map(
							(item) =>
								item && (
									<Button
										key={item.text}
										type="button"
										buttonStyle="text"
										icon={item.icon}
										onClick={() => handleActionClick(item.action, item.text)}
										disabled={isLoading}
									>
										{item.text}
									</Button>
								),
						)}
						{exportAction && <ExportButton onClick={exportAction} />}
					</S.BulkActions>
				</S.BulkActionsWrapper>
			)}
		</S.BulkHeader>
	);
};

interface IBulkSelectionProps {
	checkState: any;
	actions: (IBulkAction | undefined | null)[];
	selectItems: () => void;
	totalItems: number;
	isScrolling?: boolean;
	className?: string;
	exportAction?: (formats: (string | number)[]) => void;
	selectedItems: IBulkSelectedItems;
	isLoading: boolean;
	itemLabel: ItemLabel;
}

export default BulkSelectionOptions;
