import { createContext, useContext } from "react";

import type { EditAction, ToolProviderProps } from "../../types.js";
import { type RedactToolState, useRedactTool } from "./useRedactTool.js";

interface RedactContextValue extends RedactToolState {
	imageUrl: string;
	onApply: (blob: Blob, actions: EditAction[]) => void;
	onCancel: () => void;
}

let RedactContext = createContext<RedactContextValue | null>(null);

export function RedactProvider({ imageUrl, onApply, onCancel, children }: ToolProviderProps) {
	let state = useRedactTool(imageUrl);
	return <RedactContext.Provider value={{ ...state, imageUrl, onApply, onCancel }}>{children}</RedactContext.Provider>;
}

export function useRedactContext(): RedactContextValue {
	let ctx = useContext(RedactContext);
	if (!ctx) throw new Error("useRedactContext must be used within RedactProvider");
	return ctx;
}
