import { createContext, useContext } from "react";

import type { EditAction, ToolProviderProps } from "../../types.js";
import type { CropToolState } from "./useCropTool.js";
import { useCropTool } from "./useCropTool.js";

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

let CropContext = createContext<CropContextValue | null>(null);

export function CropProvider({ imageUrl, onApply, onCancel, children }: ToolProviderProps) {
	let state = useCropTool(imageUrl, true);
	return <CropContext.Provider value={{ ...state, imageUrl, onApply, onCancel }}>{children}</CropContext.Provider>;
}

export function useCropContext(): CropContextValue {
	let ctx = useContext(CropContext);
	if (!ctx) throw new Error("useCropContext must be used within CropProvider");
	return ctx;
}
