import { useEditorStore, type ToolType } from "@/pages/editor/store/editorStore";
import { useSingleUpload } from "@/pages/uploader/hooks/useUploaderData";
import {
    ImageUpload,
    VideoInput,
    LinkInput,
    SelectInstruction,
    RectangleInstruction,
    TextInstruction,
    LineInstruction,
    ArrowInstruction,
    StickerInstruction,
    GridInstruction,
} from "./instructions";

type ToolInstructionsProps = {
    tool: ToolType;
};

const ToolInstructions = ({ tool }: ToolInstructionsProps) => {
    const { addObject, setSelectedObjectId, setTool } = useEditorStore();
    const { mutateAsync: uploadFile } = useSingleUpload();

    const handleImageUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
        const file = e.target.files?.[0];
        if (!file) return;
        try {
            const result = await uploadFile(file);
            const imageUrl = result?.data?.url;
            if (!imageUrl) return;
            const img = new Image();
            img.onload = () => {
                const newImage = {
                    id: `image-${Date.now()}`,
                    type: "image" as ToolType,
                    x: 100,
                    y: 100,
                    width: img.width,
                    height: img.height,
                    imageUrl,
                };
                addObject(newImage);
                setSelectedObjectId(newImage.id);
                setTool("select");
            };
            img.src = imageUrl;
        } catch {
            // TODO: show error toast
        }
    };

    if (tool === "image") {
        return <ImageUpload onImageUpload={handleImageUpload} />;
    }

    if (tool === "video") {
        return <VideoInput />;
    }

    if (tool === "link") {
        return <LinkInput />;
    }

    const simpleInstructions: Partial<Record<ToolType, React.ReactElement>> = {
        select: <SelectInstruction />,
        rectangle: <RectangleInstruction />,
        text: <TextInstruction />,
        line: <LineInstruction />,
        arrow: <ArrowInstruction />,
        sticker: <StickerInstruction />,
        grid: <GridInstruction />,
    };

    return simpleInstructions[tool] ?? null;
};

export default ToolInstructions;

