"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import { useMemo, useState } from "react";
import { getCollectionDefinition } from "@byline/core";
import { Button, Checkbox, CloseIcon, ErrorText, IconButton, Input, Label, Modal, RadioGroup, RadioGroupItem, RelationPicker } from "@byline/ui/react";
import { useEditorConfig } from "../../config/editor-config-context.js";
import { useModalFormState } from "../../shared/useModalFormState.js";
import { isAltTextValid, positionOptions } from "./fields.js";
import { deriveImageSizes, getPreferredSize } from "./utils.js";
function emptyState() {
    return {
        documentRelation: null,
        altText: '',
        position: 'full',
        showCaption: false
    };
}
function fromInlineImageData(data) {
    if (!data) return emptyState();
    return {
        documentRelation: data.documentRelation ?? null,
        altText: data.altText ?? '',
        position: data.position ?? 'full',
        showCaption: data.showCaption ?? false
    };
}
const InlineImageModal = ({ isOpen, collection, data: dataFromProps, onSubmit, onClose })=>{
    const [pickerOpen, setPickerOpen] = useState(false);
    const [altError, setAltError] = useState(null);
    const [imageError, setImageError] = useState(null);
    const { config: editorSettings } = useEditorConfig();
    const [state, setState] = useModalFormState(isOpen, ()=>fromInlineImageData(dataFromProps), ()=>{
        setAltError(null);
        setImageError(null);
    });
    const targetDef = getCollectionDefinition(collection);
    const pickedImage = useMemo(()=>{
        const img = state.documentRelation?.document?.image;
        return img ?? null;
    }, [
        state.documentRelation
    ]);
    const pickedThumbUrl = useMemo(()=>{
        if (!pickedImage?.storageUrl) return null;
        if ('image/svg+xml' === pickedImage.mimeType) return pickedImage.storageUrl;
        const thumbVariant = pickedImage.variants?.find((v)=>'thumbnail' === v.name);
        return thumbVariant?.storageUrl ?? pickedImage.storageUrl;
    }, [
        pickedImage
    ]);
    const pickedTitle = useMemo(()=>{
        const title = state.documentRelation?.document?.title;
        return 'string' == typeof title && title.length > 0 ? title : null;
    }, [
        state.documentRelation
    ]);
    const handlePickerSelect = (selection)=>{
        setPickerOpen(false);
        const fields = selection.record?.fields ?? {};
        const image = fields.image;
        const title = 'string' == typeof fields.title ? fields.title : void 0;
        const altTextFromMedia = 'string' == typeof fields.altText ? fields.altText : void 0;
        const sizes = image ? deriveImageSizes(image) : [];
        setState((s)=>{
            const document = {};
            if (title) document.title = title;
            if (altTextFromMedia) document.altText = altTextFromMedia;
            if (image) document.image = image;
            if (sizes.length > 0) document.sizes = sizes;
            return {
                ...s,
                documentRelation: {
                    targetDocumentId: selection.targetDocumentId,
                    targetCollectionId: selection.targetCollectionId,
                    targetCollectionPath: collection,
                    document: Object.keys(document).length > 0 ? document : void 0
                },
                altText: s.altText.length > 0 ? s.altText : altTextFromMedia ?? ''
            };
        });
        setImageError(null);
    };
    const handleSave = ()=>{
        if (!state.documentRelation || !pickedImage) return void setImageError('Pick an image');
        if (!isAltTextValid(state.altText)) return void setAltError('Alt text is required');
        const preferred = getPreferredSize(state.position, pickedImage);
        const persistedRelation = editorSettings.embedRelationsOnSave ? state.documentRelation : {
            targetDocumentId: state.documentRelation.targetDocumentId,
            targetCollectionId: state.documentRelation.targetCollectionId,
            targetCollectionPath: state.documentRelation.targetCollectionPath
        };
        const data = {
            documentRelation: persistedRelation,
            src: preferred?.url ?? pickedImage.storageUrl ?? '',
            altText: state.altText.trim(),
            position: state.position,
            width: preferred?.width,
            height: preferred?.height,
            showCaption: state.showCaption
        };
        onSubmit(data);
        onClose();
    };
    if (!isOpen) return null;
    return /*#__PURE__*/ jsxs(Fragment, {
        children: [
            /*#__PURE__*/ jsx(Modal, {
                isOpen: isOpen,
                onDismiss: onClose,
                closeOnOverlayClick: false,
                children: /*#__PURE__*/ jsxs(Modal.Container, {
                    style: {
                        maxWidth: '520px',
                        width: '100%'
                    },
                    children: [
                        /*#__PURE__*/ jsxs(Modal.Header, {
                            className: "flex items-center justify-between pt-4 mb-2",
                            children: [
                                /*#__PURE__*/ jsx("h3", {
                                    className: "m-0 text-xl",
                                    children: "Inline image"
                                }),
                                /*#__PURE__*/ jsx(IconButton, {
                                    "aria-label": "Close",
                                    size: "xs",
                                    onClick: onClose,
                                    children: /*#__PURE__*/ jsx(CloseIcon, {
                                        width: "15px",
                                        height: "15px",
                                        svgClassName: "white-icon"
                                    })
                                })
                            ]
                        }),
                        /*#__PURE__*/ jsx(Modal.Content, {
                            children: /*#__PURE__*/ jsxs("div", {
                                className: "flex flex-col gap-4",
                                children: [
                                    /*#__PURE__*/ jsxs("div", {
                                        className: "flex flex-col gap-2",
                                        children: [
                                            /*#__PURE__*/ jsx("span", {
                                                className: "text-sm font-medium",
                                                children: "Image"
                                            }),
                                            /*#__PURE__*/ jsxs("div", {
                                                className: "flex items-center gap-3",
                                                children: [
                                                    pickedThumbUrl ? /*#__PURE__*/ jsx("img", {
                                                        src: pickedThumbUrl,
                                                        alt: pickedTitle ?? '',
                                                        className: "w-18 h-18 object-cover rounded border border-gray-700"
                                                    }) : /*#__PURE__*/ jsx("div", {
                                                        className: "w-18 h-18 flex items-center justify-center bg-gray-800 rounded border border-gray-700 text-xs text-gray-500",
                                                        children: "—"
                                                    }),
                                                    /*#__PURE__*/ jsx(Button, {
                                                        size: "sm",
                                                        className: "min-w-[70px]",
                                                        variant: "outlined",
                                                        intent: "noeffect",
                                                        type: "button",
                                                        onClick: ()=>setPickerOpen(true),
                                                        children: state.documentRelation ? 'Change image…' : `Pick ${targetDef?.labels.singular ?? 'image'}…`
                                                    }),
                                                    pickedTitle && /*#__PURE__*/ jsx("span", {
                                                        className: "text-sm text-gray-200 truncate",
                                                        children: pickedTitle
                                                    })
                                                ]
                                            }),
                                            imageError && /*#__PURE__*/ jsx(ErrorText, {
                                                id: "image-error",
                                                text: imageError
                                            })
                                        ]
                                    }),
                                    /*#__PURE__*/ jsx(Input, {
                                        id: "inline-image-alt",
                                        name: "altText",
                                        label: "Alt text",
                                        required: true,
                                        placeholder: "Describe the image for screen readers",
                                        value: state.altText,
                                        error: null != altError,
                                        errorText: altError ?? void 0,
                                        onChange: (e)=>{
                                            setAltError(null);
                                            setState((s)=>({
                                                    ...s,
                                                    altText: e.target.value
                                                }));
                                        }
                                    }),
                                    /*#__PURE__*/ jsxs("div", {
                                        className: "flex flex-col gap-2 mb-3",
                                        children: [
                                            /*#__PURE__*/ jsx(Label, {
                                                htmlFor: "inline-image-position",
                                                id: "inline-image-position-label",
                                                className: "text-sm font-medium",
                                                label: "Position"
                                            }),
                                            /*#__PURE__*/ jsx(RadioGroup, {
                                                id: "inline-image-position",
                                                name: "position",
                                                "aria-labelledby": "inline-image-position-label",
                                                direction: "row",
                                                value: state.position ?? 'full',
                                                onValueChange: (value)=>setState((s)=>({
                                                            ...s,
                                                            position: value
                                                        })),
                                                children: positionOptions.map((opt)=>/*#__PURE__*/ jsx(RadioGroupItem, {
                                                        id: `inline-image-position-${opt.value}`,
                                                        value: String(opt.value),
                                                        label: opt.label
                                                    }, String(opt.value)))
                                            })
                                        ]
                                    }),
                                    /*#__PURE__*/ jsx(Checkbox, {
                                        id: "inline-image-caption",
                                        name: "showCaption",
                                        label: "Show caption",
                                        checked: state.showCaption,
                                        onCheckedChange: (checked)=>setState((s)=>({
                                                    ...s,
                                                    showCaption: true === checked
                                                }))
                                    })
                                ]
                            })
                        }),
                        /*#__PURE__*/ jsxs(Modal.Actions, {
                            className: "flex gap-3",
                            children: [
                                /*#__PURE__*/ jsx(Button, {
                                    size: "sm",
                                    intent: "noeffect",
                                    type: "button",
                                    onClick: onClose,
                                    className: "min-w-[70px]",
                                    children: "Cancel"
                                }),
                                /*#__PURE__*/ jsx(Button, {
                                    size: "sm",
                                    intent: "primary",
                                    type: "button",
                                    onClick: handleSave,
                                    className: "min-w-[70px]",
                                    children: "Save"
                                })
                            ]
                        })
                    ]
                })
            }),
            /*#__PURE__*/ jsx(RelationPicker, {
                targetCollectionPath: collection,
                targetDefinition: targetDef,
                isOpen: pickerOpen,
                onSelect: handlePickerSelect,
                onDismiss: ()=>setPickerOpen(false)
            })
        ]
    });
};
export { InlineImageModal };
