import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { Dialog, DialogContent, DialogHeader, DialogTitle, } from "../components/ui/dialog";
import { useEditContext } from "./client/editContext";
import { useCallback, useEffect, useState } from "react";
import { Button } from "../components/ui/button";
import DialogButtons from "./ui/DialogButtons";
import { AlertTriangle, Pencil } from "lucide-react";
import { getPictureValue } from "./services/editService";
import { getRenderedPictureVariant, } from "./picture-shared";
export function PictureEditorDialog({ field, onCancel, onOk, params, }) {
    const [selectedVariantName, setSelectedVariantName] = useState();
    const [pictureValue, setPictureValue] = useState();
    const [rawValue, setRawValue] = useState();
    const emptyRect = () => ({
        width: 0,
        height: 0,
        top: 0,
        left: 0,
    });
    const [rect, setRect] = useState(emptyRect());
    const editContext = useEditContext();
    useEffect(() => {
        setSelectedVariantName(field?.value?.variants[0].name);
    }, []);
    useEffect(() => {
        const deepCopy = JSON.parse(JSON.stringify(field.value));
        setPictureValue(deepCopy);
        const raw = field?.rawValue
            ? JSON.parse(field?.rawValue)
            : { Variants: [] };
        setRawValue(raw);
        if (!field?.value?.variants[0].src)
            selectMedia(field?.value?.variants[0].name, raw);
    }, [field]);
    async function selectMedia(variantName, raw) {
        const chosenImage = await editContext?.selectMedia({
            selectedIdPath: selectedVariant?.idPath || "",
            mode: "images",
        });
        if (chosenImage)
            imageSelected(chosenImage, variantName ?? selectedVariantName, raw ?? rawValue);
    }
    const selectedVariant = pictureValue && pictureValue.variants
        ? pictureValue.variants?.find((x) => x.name == selectedVariantName)
        : null;
    useEffect(() => {
        if (selectedVariant?.region &&
            (!selectedVariant.aspectRatioLock ||
                Math.abs(selectedVariant.aspectRatioLock -
                    selectedVariant.region.width / selectedVariant.region.height) < 0.1))
            setRect({
                width: selectedVariant.region.width,
                height: selectedVariant.region.height,
                top: selectedVariant.region.y,
                left: selectedVariant.region.x,
            });
        else {
            setRect(emptyRect());
        }
    }, [selectedVariantName]);
    const getPictureFieldValue = async (field, rawValue) => {
        if (!editContext)
            return null;
        const pageViewContext = editContext?.getActiveSlotContext()?.primaryPageViewContext;
        if (!pageViewContext?.site)
            return null;
        return getPictureValue(field, rawValue, pageViewContext.site?.name, editContext.sessionId);
    };
    const imageSelected = useCallback(async (imageId, variantName, rawValue) => {
        if (!variantName || !rawValue)
            return;
        const selected = rawValue.Variants?.find((x) => x.Name == variantName);
        if (!selected) {
            if (!rawValue.Variants)
                rawValue.Variants = [];
            rawValue.Variants.push({
                Name: variantName,
                MediaId: imageId,
            });
        }
        else {
            selected.MediaId = imageId;
        }
        setRawValue(rawValue);
        const newValue = await getPictureFieldValue(field, rawValue);
        if (newValue) {
            setPictureValue(newValue);
        }
    }, []);
    const updateRawValue = async (rawValue) => {
        setRawValue(rawValue);
        const newValue = await getPictureFieldValue(field, rawValue);
        if (newValue) {
            setPictureValue(newValue);
        }
    };
    const setVariantCrop = async () => {
        if (!rawValue)
            return;
        if (!selectedVariantName)
            return;
        if (selectedVariant) {
            let selected = rawValue.Variants?.find((x) => x.Name == selectedVariantName);
            if (!selected) {
                selected = {
                    Name: selectedVariantName,
                    MediaId: selectedVariant.mediaId,
                };
                rawValue.Variants?.push(selected);
            }
            if (selected) {
                selected.Region = {
                    X: rect.left,
                    Y: rect.top,
                    Width: rect.width,
                    Height: rect.height,
                };
                await updateRawValue(rawValue);
            }
        }
    };
    const usage = getUsage(pictureValue, params);
    return (_jsx(_Fragment, { children: _jsx(Dialog, { open: true, onOpenChange: (open) => {
                if (!open) {
                    onCancel();
                }
            }, children: _jsxs(DialogContent, { className: "max-w-none", style: { width: "70vw", height: "70vh" }, children: [_jsx(DialogHeader, { children: _jsx(DialogTitle, { children: "Edit " + field.name }) }), _jsx("div", { className: "flex-1 overflow-auto", children: _jsxs("div", { className: "justify flex h-full flex-col gap-1", children: [_jsxs("div", { className: "flex flex-1 gap-2", children: [_jsxs("div", { className: "relative h-full w-48 border-r pt-3", children: [_jsx("div", { className: "absolute inset-0 flex flex-col gap-6 overflow-y-auto", children: pictureValue &&
                                                        pictureValue.variants?.map((variant) => (_jsxs("div", { onClick: () => setSelectedVariantName(variant.name), className: "flex cursor-pointer flex-col items-center justify-center gap-1 text-xs", children: [_jsx("div", { className: "relative flex h-40 w-40 items-center justify-center border" +
                                                                        (selectedVariantName == variant.name
                                                                            ? " shadow-xl"
                                                                            : ""), children: variant.src && _jsx("img", { src: variant.thumbSrc }) }), _jsxs("div", { className: "w-40", children: [_jsx("div", { children: variant.name }), _jsx("div", { children: variant.aspectRatioLockText }), _jsxs("div", { children: [_jsxs("div", { className: "break-all", children: ["Name: ", variant.mediaItemName] }), _jsxs("div", { children: ["Orig. size: ", variant.width, " x ", variant.height] }), (variant.width < 1 || variant.height < 1) && (_jsxs("span", { children: [" ", _jsx(AlertTriangle, { className: "inline h-4 w-4 text-red-600" })] }))] })] })] }, variant.name))) }), usage && _jsx("div", { className: "text-xs", children: usage })] }), _jsx("div", { className: "relative flex-1 p-3", children: _jsxs("div", { className: "align-center absolute inset-0 top-3 flex justify-center overflow-auto select-none", children: [selectedVariant && (_jsxs("div", { className: "relative", onDoubleClick: () => selectMedia(), onMouseDown: (ev) => {
                                                            ev.preventDefault();
                                                            ev.stopPropagation();
                                                            const bounds = ev.currentTarget.getBoundingClientRect();
                                                            setRect({
                                                                left: (ev.clientX - bounds.left) / bounds.width,
                                                                top: (ev.clientY - bounds.top) / bounds.height,
                                                                width: 0,
                                                                height: 0,
                                                            });
                                                        }, onMouseMoveCapture: (ev) => {
                                                            if (ev.buttons === 1) {
                                                                const bounds = ev.currentTarget.getBoundingClientRect();
                                                                const width = (ev.clientX - bounds.left) / bounds.width -
                                                                    rect.left;
                                                                const newRect = {
                                                                    ...rect,
                                                                    width,
                                                                    height: selectedVariant.aspectRatioLock
                                                                        ? width / selectedVariant.aspectRatioLock
                                                                        : (ev.clientY - bounds.top) / bounds.height -
                                                                            rect.top,
                                                                };
                                                                setRect(newRect);
                                                                ev.preventDefault();
                                                                ev.stopPropagation();
                                                            }
                                                        }, onMouseUp: () => setVariantCrop(), children: [_jsx("img", { src: selectedVariant.originalSrc ?? selectedVariant.src, className: "h-full w-full object-contain" }), _jsx("div", { className: "bg-opacity-70 absolute bg-gray-300", style: {
                                                                    left: rect.left * 100 + "%",
                                                                    top: rect.top * 100 + "%",
                                                                    width: rect.width * 100 + "%",
                                                                    height: rect.height * 100 + "%",
                                                                } })] })), selectedVariant && (_jsxs("div", { className: "bg-opacity-70 absolute top-0 right-0 flex cursor-pointer flex-col items-center gap-1 bg-gray-100 p-2 text-sm", onClick: () => selectMedia(), children: [_jsx(Pencil, { className: "h-5 w-5" }), "Choose"] }))] }) })] }), _jsxs(DialogButtons, { children: [_jsx(Button, { onClick: () => {
                                                onCancel();
                                            }, size: "sm", children: "Cancel" }), _jsx(Button, { size: "sm", onClick: () => {
                                                if (pictureValue) {
                                                    if (field) {
                                                        editContext?.operations.editField({
                                                            field: field.descriptor,
                                                            rawValue: JSON.stringify(rawValue),
                                                            refresh: "immediate",
                                                        });
                                                    }
                                                    onOk(pictureValue);
                                                }
                                            }, children: "Ok" })] })] }) })] }) }) }));
}
function getUsage(pictureValue, params) {
    if (!params)
        return;
    if (!pictureValue)
        return;
    if (pictureValue.variants.length <= 1)
        return;
    const mediaParams = typeof params === "object" && "default" in params ? params : undefined;
    if (mediaParams) {
        const sources = Object.keys(mediaParams ?? {});
        const variants = sources
            .map((source) => ({
            source,
            variant: getRenderedPictureVariant(mediaParams[source], pictureValue.variants),
        }))
            .filter((x) => x.variant);
        return (_jsxs(_Fragment, { children: ["This field rendering is using these variants:", _jsx("table", { children: variants.map((v) => (_jsxs("tr", { children: [_jsx("td", { children: v.source }), _jsx("td", { children: _jsx("b", { children: v.variant.name }) })] }))) })] }));
    }
    return (_jsxs(_Fragment, { children: ["This field rendering is using the variant", " ", _jsxs("b", { children: [getRenderedPictureVariant(params, pictureValue.variants)?.name, "."] })] }));
}
//# sourceMappingURL=PictureEditorDialog.js.map