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

import { useRedactContext } from "./RedactContext.js";

/** Toolbar shown while the redact tool is active. Reads state from RedactContext. */
export function RedactToolbar() {
	let { rects, clearAll, applyRedact, onApply, onCancel } = useRedactContext();
	let [applying, setApplying] = useState(false);

	async function handleApply() {
		if (rects.length === 0) {
			onCancel();
			return;
		}
		setApplying(true);
		try {
			let result = await applyRedact();
			if (result) onApply(result.blob, result.actions);
		} finally {
			setApplying(false);
		}
	}

	return (
		<>
			<div className="image-editor__toolbar-group">
				<Button variant="tertiary" data-size="sm" onClick={onCancel} disabled={applying}>
					<XMarkIcon aria-hidden />
					{getLocalizedString("Cancel")}
				</Button>
				<Button variant="tertiary" data-size="sm" onClick={clearAll} disabled={applying || rects.length === 0}>
					<EraserIcon aria-hidden />
					{getLocalizedString("Clear all")}
				</Button>
			</div>
			<div className="image-editor__toolbar-group">
				<Button variant="primary" data-size="sm" onClick={handleApply} disabled={applying}>
					{applying ? <Spinner aria-hidden data-size="xs" /> : <CheckmarkIcon aria-hidden />}
					{rects.length === 0 ? getLocalizedString("Done") : getLocalizedString("Apply redact")}
				</Button>
			</div>
		</>
	);
}
