import { Button, Spinner } from "@digdir/designsystemet-react";
import { CheckmarkIcon, ExpandIcon, SquareIcon, XMarkIcon } from "@navikt/aksel-icons";
import { getLocalizedString } from "@olenbetong/appframe-core";

import { useCropContext } from "./CropContext.js";

/** Toolbar shown while the crop tool is active. Reads state from CropContext. */
export function CropToolbar() {
	let { applyCrop, cropping, mode, hasSelection, startRectMode, cancelRectMode, onApply, onCancel } = useCropContext();
	let inRectMode = mode === "rect";

	async function handleApply() {
		let result = await applyCrop();
		if (result) onApply(result.blob, result.actions);
	}

	return (
		<>
			<div className="image-editor__toolbar-group">
				<Button variant="tertiary" data-size="sm" onClick={onCancel} disabled={cropping}>
					<XMarkIcon aria-hidden />
					{getLocalizedString("Cancel")}
				</Button>
			</div>
			<div className="image-editor__toolbar-group">
				<Button
					variant="tertiary"
					data-size="sm"
					aria-pressed={inRectMode}
					onClick={inRectMode ? cancelRectMode : startRectMode}
					disabled={cropping}
				>
					{inRectMode ? <ExpandIcon aria-hidden /> : <SquareIcon aria-hidden />}
					{inRectMode ? getLocalizedString("Adjust corners") : getLocalizedString("Draw rectangle")}
				</Button>
				<Button
					variant="primary"
					data-size="sm"
					onClick={handleApply}
					disabled={cropping || inRectMode || !hasSelection}
				>
					{cropping ? <Spinner aria-hidden data-size="xs" /> : <CheckmarkIcon aria-hidden />}
					{getLocalizedString("Apply crop")}
				</Button>
			</div>
		</>
	);
}
