import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useCallback, useEffect, useState } from "react";
import { useEditContext, useEditContextRef } from "./client/editContext";
import { ImageEditButton } from "./ImageEditButton";
import { Zap, Image as ImageIcon, Sparkles } from "lucide-react";
import { AiImageEditorDialog } from "./ai-image-editor";
import { LicenseFeatures, useFeature } from "../licensing";
export function ImageEditor({ field, style, forwardScrollevents, isPageEditor, onContextMenu, onDialogOpenChange, onForwardWheel, }) {
    const editContext = useEditContext();
    const editContextRef = useEditContextRef();
    const canUseAi = useFeature(LicenseFeatures.AI);
    //const dialogContext = useDialog();
    // AI Image Editor state
    const [showAiImageEditor, setShowAiImageEditor] = useState(false);
    const [isMenuOpen, setIsMenuOpen] = useState(false);
    const [aiEditOriginalRawValue, setAiEditOriginalRawValue] = useState(null);
    useEffect(() => {
        onDialogOpenChange?.(showAiImageEditor || isMenuOpen);
    }, [showAiImageEditor, isMenuOpen, onDialogOpenChange]);
    if (!field || !editContext)
        return null;
    const imageSelected = useCallback(async (imageId) => {
        editContext.operations.editField({
            field: field.descriptor,
            rawValue: '<image mediaid="{' + imageId + '}" />',
            refresh: "immediate",
        });
    }, [field]);
    async function selectMedia() {
        const selectedImageId = await editContext?.selectMedia({
            selectedIdPath: field.value?.idPath || "",
            mode: "images",
        });
        if (selectedImageId)
            imageSelected(selectedImageId);
    }
    // Handle opening AI image editor
    const handleOpenAiImageEditor = useCallback(() => {
        // Store original value for potential revert
        setAiEditOriginalRawValue(field.rawValue || "");
        setShowAiImageEditor(true);
    }, [field.rawValue]);
    // Handle AI edit complete
    const handleAiEditComplete = useCallback((result) => {
        setShowAiImageEditor(false);
        const ctx = editContextRef.current;
        if (result.success && ctx) {
            // Trigger field action to show progress indicator on the image
            ctx.addFieldAction({
                field: field.descriptor,
                label: "AI Image Edit",
                state: "running",
                message: "Generating image...",
            });
        }
    }, [field.descriptor, editContextRef]);
    const getImageSrc = () => {
        if (!field.value) {
            if (!field.rawValue)
                return null;
            const parser = new DOMParser();
            const xmlDoc = parser.parseFromString(field.rawValue, "text/xml");
            const imageElement = xmlDoc.documentElement;
            return imageElement.getAttribute("src");
        }
        return field.value.src;
    };
    const getImageAlt = () => {
        if (!field.value)
            return "";
        // Standard image
        return field.value.alt;
    };
    // Helper function to render icon
    const renderIcon = (icon) => {
        if (!icon) {
            return _jsx(Zap, { strokeWidth: 1, size: 16 });
        }
        if (typeof icon === "string") {
            return _jsx("img", { src: icon, alt: "", className: "h-4 w-4" });
        }
        return icon;
    };
    // Check if AI image edit is enabled for this field type
    const aiImageEditEnabled = canUseAi &&
        editContext?.configuration?.fieldTypes?.image?.aiImageEdit !== false;
    // Build actions for the dropdown menu
    const menuActions = [
        {
            id: "select",
            label: getImageSrc() ? "Change Image" : "Select Image",
            icon: _jsx(ImageIcon, { strokeWidth: 1, size: 16 }),
            onClick: () => selectMedia(),
        },
        // AI Image Edit action (if enabled)
        ...(aiImageEditEnabled
            ? [
                {
                    id: "ai-image-edit",
                    label: "AI Edit",
                    icon: _jsx(Sparkles, { strokeWidth: 1, size: 16 }),
                    onClick: () => handleOpenAiImageEditor(),
                },
            ]
            : []),
        ...(editContext?.configuration?.fieldTypes["image"]?.buttons?.map((button) => ({
            id: button.id,
            label: button.label,
            icon: renderIcon(button.icon),
            onClick: (event) => {
                button?.clientAction?.({
                    field,
                    editContext,
                    event,
                    //dialogContext,
                });
            },
        })) || []),
    ];
    return (_jsxs("div", { className: "pointer-events-auto absolute inset-0 flex items-center justify-center", style: style, "data-testid": "select-media", onMouseDown: (e) => {
            if (!isPageEditor)
                return;
            const itemId = field.descriptor.item?.id;
            if (itemId) {
                editContext?.select([itemId]);
            }
            e.stopPropagation();
        }, onContextMenu: onContextMenu, onWheel: (e) => {
            if (!forwardScrollevents)
                return;
            onForwardWheel?.(e);
        }, children: [getImageSrc() && (_jsx("img", { src: getImageSrc(), alt: getImageAlt(), className: "max-h-full max-w-full object-contain" })), _jsx(ImageEditButton, { actions: menuActions, compact: false, buttonText: "Edit", testId: "select-media-button", onOpenChange: setIsMenuOpen }), canUseAi && showAiImageEditor && (_jsx(AiImageEditorDialog, { open: showAiImageEditor, onClose: () => {
                    setShowAiImageEditor(false);
                    setAiEditOriginalRawValue(null);
                }, onComplete: handleAiEditComplete, fieldDescriptor: field.descriptor, originalRawValue: aiEditOriginalRawValue || "", currentImageSrc: getImageSrc() || undefined }))] }));
}
//# sourceMappingURL=ImageEditor.js.map