"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import { useMemo, useState } from "react";
import { getClientConfig, getCollectionDefinition } from "@byline/core";
import { Button, Checkbox, CloseIcon, IconButton, Input, Label, Modal, RadioGroup, RadioGroupItem, RelationPicker, Select } from "@byline/ui/react";
import { useEditorConfig } from "../../../config/editor-config-context.js";
import { useModalFormState } from "../../../shared/useModalFormState.js";
import { validateUrl } from "../../../utils/url.js";
function emptyState(linkable) {
    return {
        text: '',
        linkType: linkable.length > 0 ? 'internal' : 'custom',
        url: '',
        newTab: false,
        targetCollection: linkable[0]?.path ?? null,
        picked: null
    };
}
function fromLinkData(data, linkable) {
    const base = emptyState(linkable);
    if (!data) return base;
    const fields = data.fields;
    if (!fields) return base;
    const url = 'internal' === fields.linkType ? '' : fields.url ?? '';
    const isPlaceholderUrl = '' === url || 'https://' === url;
    const wantsInternal = linkable.length > 0 && ('internal' === fields.linkType || isPlaceholderUrl);
    const linkType = wantsInternal ? 'internal' : 'custom';
    const picked = 'internal' === fields.linkType ? {
        targetDocumentId: fields.targetDocumentId,
        targetCollectionId: fields.targetCollectionId,
        targetCollectionPath: fields.targetCollectionPath,
        document: fields.document
    } : null;
    return {
        text: data.text ?? '',
        linkType,
        url: isPlaceholderUrl ? '' : url,
        newTab: fields.newTab ?? false,
        targetCollection: picked?.targetCollectionPath ?? linkable[0]?.path ?? null,
        picked
    };
}
const LinkModal = ({ isOpen = false, onSubmit, onClose, data: dataFromProps })=>{
    const linkable = useMemo(()=>getClientConfig().collections.filter((c)=>true === c.linksInEditor), []);
    const [pickerOpen, setPickerOpen] = useState(false);
    const [urlError, setUrlError] = useState(null);
    const { config: editorSettings } = useEditorConfig();
    const [state, setState] = useModalFormState(isOpen, ()=>fromLinkData(dataFromProps, linkable), ()=>setUrlError(null));
    const targetDef = state.targetCollection ? getCollectionDefinition(state.targetCollection) : null;
    const collectionItems = useMemo(()=>linkable.map((c)=>({
                label: c.labels.singular,
                value: c.path
            })), [
        linkable
    ]);
    const pickedLabel = useMemo(()=>{
        if ('internal' !== state.linkType || !state.picked) return null;
        const title = state.picked.document?.title;
        if ('string' == typeof title && title.length > 0) return title;
        const pickedDef = getCollectionDefinition(state.picked.targetCollectionPath);
        const short = state.picked.targetDocumentId.slice(0, 8);
        return `${pickedDef?.labels.singular ?? state.picked.targetCollectionPath} · ${short}…`;
    }, [
        state.linkType,
        state.picked
    ]);
    const handlePickerSelect = (selection)=>{
        setPickerOpen(false);
        setState((s)=>{
            const targetCollection = s.targetCollection;
            const titleField = getCollectionDefinition(targetCollection)?.useAsTitle;
            const title = titleField ? selection.record?.fields?.[titleField] : void 0;
            const path = selection.record?.path;
            const document = {};
            if ('string' == typeof title && title.length > 0) document.title = title;
            if ('string' == typeof path && path.length > 0) document.path = path;
            return {
                ...s,
                picked: {
                    targetDocumentId: selection.targetDocumentId,
                    targetCollectionId: selection.targetCollectionId,
                    targetCollectionPath: targetCollection,
                    document: Object.keys(document).length > 0 ? document : void 0
                }
            };
        });
    };
    const handleSave = ()=>{
        if ('custom' === state.linkType) {
            const url = state.url;
            if (!url.startsWith('/') && !validateUrl(url)) return void setUrlError('Enter a valid URL or a root-relative path starting with /');
        }
        if ('internal' === state.linkType) {
            if (!state.picked) return void setUrlError('Pick a target document');
        }
        const picked = state.picked;
        const fields = 'custom' === state.linkType ? {
            linkType: 'custom',
            url: state.url,
            newTab: state.newTab
        } : {
            linkType: 'internal',
            newTab: state.newTab,
            targetDocumentId: picked.targetDocumentId,
            targetCollectionId: picked.targetCollectionId,
            targetCollectionPath: picked.targetCollectionPath,
            document: editorSettings.embedRelationsOnSave ? picked.document : void 0
        };
        onSubmit({
            text: state.text.length > 0 ? state.text : null,
            fields
        });
        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: '480px',
                        width: '100%'
                    },
                    children: [
                        /*#__PURE__*/ jsxs(Modal.Header, {
                            className: "flex items-center justify-between pt-4 mb-4",
                            children: [
                                /*#__PURE__*/ jsx("h3", {
                                    className: "m-0 text-xl",
                                    children: "Edit link"
                                }),
                                /*#__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__*/ jsx(Input, {
                                        id: "link-text",
                                        className: "mb-2",
                                        name: "text",
                                        label: "Link text",
                                        placeholder: "Visible link text",
                                        value: state.text,
                                        onChange: (e)=>setState((s)=>({
                                                    ...s,
                                                    text: e.target.value
                                                }))
                                    }),
                                    linkable.length > 0 && /*#__PURE__*/ jsxs(RadioGroup, {
                                        id: "link-type",
                                        name: "linkType",
                                        "aria-label": "Link type",
                                        direction: "row",
                                        value: state.linkType,
                                        onValueChange: (value)=>setState((s)=>({
                                                    ...s,
                                                    linkType: 'internal' === value ? 'internal' : 'custom'
                                                })),
                                        children: [
                                            /*#__PURE__*/ jsx(RadioGroupItem, {
                                                id: "link-type-internal",
                                                value: "internal",
                                                label: "Document"
                                            }),
                                            /*#__PURE__*/ jsx(RadioGroupItem, {
                                                id: "link-type-custom",
                                                value: "custom",
                                                label: "Custom URL"
                                            })
                                        ]
                                    }),
                                    'custom' === state.linkType && /*#__PURE__*/ jsx(Input, {
                                        id: "link-url",
                                        name: "url",
                                        label: "URL",
                                        placeholder: "https://example.com or /path",
                                        value: state.url,
                                        errorText: urlError ?? void 0,
                                        error: null != urlError,
                                        onChange: (e)=>{
                                            setUrlError(null);
                                            setState((s)=>({
                                                    ...s,
                                                    url: e.target.value
                                                }));
                                        }
                                    }),
                                    'internal' === state.linkType && /*#__PURE__*/ jsxs("div", {
                                        className: "flex flex-col gap-3 mt-2",
                                        children: [
                                            linkable.length > 1 && /*#__PURE__*/ jsxs("div", {
                                                children: [
                                                    /*#__PURE__*/ jsx(Label, {
                                                        id: "link-target-collection",
                                                        htmlFor: "link-target-collection",
                                                        className: "mb-1",
                                                        label: "Target collection"
                                                    }),
                                                    /*#__PURE__*/ jsx(Select, {
                                                        size: "sm",
                                                        items: collectionItems,
                                                        placeholder: "Target collection",
                                                        value: state.targetCollection ?? void 0,
                                                        onValueChange: (value)=>{
                                                            if (null == value) return;
                                                            setState((s)=>({
                                                                    ...s,
                                                                    targetCollection: value
                                                                }));
                                                        }
                                                    })
                                                ]
                                            }),
                                            /*#__PURE__*/ jsxs("div", {
                                                className: "border rounded p-3",
                                                children: [
                                                    /*#__PURE__*/ jsx(Label, {
                                                        id: "link-target-document",
                                                        htmlFor: "link-target-document",
                                                        className: "mb-1",
                                                        label: "Target document"
                                                    }),
                                                    /*#__PURE__*/ jsxs("div", {
                                                        className: "flex items-center justify-between gap-2",
                                                        children: [
                                                            pickedLabel && /*#__PURE__*/ jsx("span", {
                                                                className: "text-sm text-accent-400 truncate",
                                                                children: pickedLabel
                                                            }),
                                                            /*#__PURE__*/ jsx(Button, {
                                                                size: "sm",
                                                                variant: "outlined",
                                                                intent: "noeffect",
                                                                type: "button",
                                                                onClick: ()=>setPickerOpen(true),
                                                                disabled: !state.targetCollection,
                                                                children: pickedLabel ? 'Change' : `Pick ${targetDef?.labels.singular ?? 'document'}…`
                                                            })
                                                        ]
                                                    })
                                                ]
                                            }),
                                            urlError && 'internal' === state.linkType && /*#__PURE__*/ jsx("span", {
                                                className: "text-xs text-red-400",
                                                children: urlError
                                            })
                                        ]
                                    }),
                                    /*#__PURE__*/ jsx(Checkbox, {
                                        id: "link-new-tab",
                                        name: "newTab",
                                        label: "Open in new tab",
                                        checked: state.newTab,
                                        onCheckedChange: (checked)=>setState((s)=>({
                                                    ...s,
                                                    newTab: 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"
                                })
                            ]
                        })
                    ]
                })
            }),
            'internal' === state.linkType && state.targetCollection && /*#__PURE__*/ jsx(RelationPicker, {
                targetCollectionPath: state.targetCollection,
                targetDefinition: targetDef,
                isOpen: pickerOpen,
                onSelect: handlePickerSelect,
                onDismiss: ()=>setPickerOpen(false)
            })
        ]
    });
};
export { LinkModal };
