import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useEffect, useRef, useState } from "react";
import { Dialog, DialogContent, } from "../components/ui/dialog";
import { StyledDialogTitle } from "../components/ui/styled-dialog-title";
import { Input } from "../components/ui/input";
import { Button } from "../components/ui/button";
import { Select } from "../components/ui/select";
import ItemSearch from "./ui/ItemSearch";
import { ScrollingContentTree } from "./ScrollingContentTree";
import { useEditContext } from "./client/editContext";
import { normalizeUrl } from "./utils/urlUtils";
import DialogButtons from "./ui/DialogButtons";
import { Link2 } from "lucide-react";
function normalizeItemId(id) {
    if (!id)
        return undefined;
    return id.toLowerCase().replace(/[{}]/g, "");
}
export function LinkEditorDialog({ linkValue, onCancel, onOk, showText, }) {
    const [url, setUrl] = useState();
    const [targetWindow, setTargetWindow] = useState();
    const [customTarget, setCustomTarget] = useState();
    const [queryString, setQueryString] = useState();
    const [text, setText] = useState();
    const [activeTabIndex, setActiveTabIndex] = useState(0);
    const [selectedItemId, setSelectedItemId] = useState("");
    const [hoveredItemId, setHoveredItemId] = useState();
    const editContext = useEditContext();
    const lastInitKeyRef = useRef(null);
    useEffect(() => {
        const initKey = [
            linkValue.type,
            linkValue.itemId ?? "",
            linkValue.url ?? "",
            linkValue.target ?? "",
            linkValue.queryString ?? "",
            linkValue.text ?? "",
            linkValue.originalHref ?? "",
        ].join("|");
        if (lastInitKeyRef.current === initKey)
            return;
        lastInitKeyRef.current = initKey;
        setUrl(linkValue.url);
        setTargetWindow(linkValue.target ?? "");
        if (linkValue.type == "external")
            setActiveTabIndex(1);
        else
            setActiveTabIndex(0);
        if (linkValue.target && linkValue.target != "_blank") {
            setTargetWindow("custom");
            setCustomTarget(linkValue.target);
        }
        if (linkValue.itemId)
            setSelectedItemId(linkValue.itemId);
        if (linkValue.queryString)
            setQueryString(linkValue.queryString);
        if (linkValue.text)
            setText(linkValue.text);
    }, [linkValue]);
    const targetWindows = [
        { name: "Active browser", code: "" },
        { name: "New browser", code: "_blank" },
        { name: "Custom", code: "custom" },
    ];
    const targetWindowOptions = targetWindows.map((x) => ({
        value: x.code,
        label: x.name,
    }));
    function getTargetWindow() {
        if (targetWindow == "custom")
            return customTarget;
        return targetWindow;
    }
    if (!editContext)
        return null;
    const selectedExpansionId = normalizeItemId(selectedItemId || linkValue.itemId);
    const currentItemExpansionId = normalizeItemId(editContext.currentItemDescriptor?.id);
    const expandedItemId = selectedExpansionId || currentItemExpansionId;
    const linkTypeOptions = [
        { value: "internal", label: "Internal" },
        { value: "external", label: "External" },
    ];
    const internalContent = (_jsxs("div", { className: "flex h-full flex-col overflow-hidden", "data-testid": "internal-tab", children: [_jsx("div", { className: "border-b border-gray-100 bg-gray-50/30 p-2", children: _jsx(ItemSearch, { resultClassName: "px-2 py-1", itemSelected: (item) => {
                        setSelectedItemId(item.id);
                    }, setHoveredItem: (item) => ((item) => {
                        if (!item)
                            return;
                        setHoveredItemId(item.id);
                    })(item) }) }), _jsx("div", { className: "relative flex-1 min-h-0", children: _jsx("div", { className: "absolute inset-0 overflow-auto p-1", children: _jsx(ScrollingContentTree, { selectedItemId: hoveredItemId || selectedItemId, expandedItemId: expandedItemId, onSelectionChange: (selection) => {
                            setSelectedItemId(selection[0]?.id || "");
                        } }) }) })] }));
    const externalContent = (_jsxs("div", { className: "flex flex-col gap-2 p-3", "data-testid": "external-tab", children: [_jsx("label", { className: "block text-xs", htmlFor: "link-url-external", children: "External Url" }), _jsx(Input, { id: "link-url-external", value: url || "", onChange: (e) => {
                    setUrl(e.target.value);
                }, onBlur: (e) => {
                    const normalizedUrl = normalizeUrl(e.target.value.trim());
                    setUrl(normalizedUrl);
                }, className: "w-full text-sm", "data-testid": "link-url-external" })] }));
    useEffect(() => {
        // Trigger a resize event to recalculate layouts when dialog opens
        window.dispatchEvent(new Event("resize"));
    }, []);
    return (_jsx(Dialog, { open: true, onOpenChange: (open) => {
            if (!open)
                onCancel();
        }, "data-testid": "link-editor-dialog", children: _jsxs(DialogContent, { className: "flex flex-col overflow-hidden border-none p-0 shadow-2xl", style: { width: "80vw", maxWidth: "900px", height: "70vh", maxHeight: "750px" }, children: [_jsx(StyledDialogTitle, { icon: _jsx(Link2, { strokeWidth: 1 }), title: "Select link target" }), _jsxs("div", { className: "flex min-h-0 flex-1 flex-col overflow-hidden", children: [_jsx("div", { className: "flex min-h-0 flex-1 flex-col overflow-y-auto px-6 pb-4", children: _jsxs("div", { className: "flex min-h-0 flex-1 flex-col gap-6 pt-6", children: [linkValue && (_jsx("div", { className: "flex items-center gap-8", children: linkTypeOptions.map((option) => (_jsxs("label", { className: "flex cursor-pointer items-center gap-2.5", children: [_jsx("input", { type: "radio", name: "link-type", value: option.value, checked: activeTabIndex ===
                                                        (option.value === "internal" ? 0 : 1), onClick: () => {
                                                        setActiveTabIndex(option.value === "internal" ? 0 : 1);
                                                    }, onChange: () => { }, className: "h-4 w-4 cursor-pointer accent-primary", "data-testid": `link-type-${option.value}` }), _jsx("span", { className: "text-sm font-medium text-gray-700", children: option.label })] }, option.value))) })), _jsxs("div", { className: "flex min-h-0 flex-1 flex-col gap-4", children: [_jsx("div", { className: `overflow-hidden bg-white ${activeTabIndex === 0
                                                    ? "flex-1 min-h-[320px]"
                                                    : "min-h-[110px] rounded-xl border border-gray-200 shadow-sm"}`, children: activeTabIndex === 0 ? internalContent : externalContent }), _jsxs("div", { className: "grid grid-cols-2 gap-6", children: [_jsxs("div", { className: "flex flex-col gap-4", children: [showText && (_jsxs("div", { className: "flex flex-col gap-2", children: [_jsx("label", { className: "text-sm font-semibold text-gray-900", children: "Link description" }), _jsx(Input, { value: text || "", onChange: (e) => setText(e.target.value), className: "bg-white", placeholder: "Enter link text..." })] })), _jsxs("div", { className: "flex flex-col gap-2", children: [_jsx("label", { className: "text-sm font-semibold text-gray-900", children: "Query String" }), _jsx(Input, { value: queryString || "", onChange: (e) => setQueryString(e.target.value), className: "bg-white", placeholder: "e.g. ?id=123" })] })] }), _jsxs("div", { className: "flex flex-col gap-4", children: [_jsxs("div", { className: "flex flex-col gap-2", children: [_jsx("label", { className: "text-sm font-semibold text-gray-900", children: "Window" }), _jsx(Select, { value: targetWindow, onValueChange: (v) => setTargetWindow(v), options: targetWindowOptions, placeholder: "Select window", className: "bg-white" })] }), targetWindow === "custom" && (_jsxs("div", { className: "flex flex-col gap-2", children: [_jsx("label", { className: "text-sm font-semibold text-gray-900", children: "Custom Window Name" }), _jsx(Input, { value: customTarget || "", onChange: (e) => {
                                                                            setCustomTarget(e.target.value);
                                                                        }, placeholder: "Enter window name", className: "bg-white" })] }))] })] })] })] }) }), _jsxs(DialogButtons, { hideBorder: true, className: "bg-gray-50/50", children: [_jsx(Button, { variant: "ghost", onClick: onCancel, "data-testid": "dialog-cancel", children: "Cancel" }), _jsx(Button, { onClick: () => {
                                        const isExternal = activeTabIndex === 1;
                                        onOk({
                                            url: isExternal ? normalizeUrl(url || "") : url,
                                            target: getTargetWindow(),
                                            customTarget: customTarget,
                                            itemId: selectedItemId,
                                            queryString: queryString,
                                            text: text,
                                            type: isExternal ? "external" : "internal",
                                        });
                                    }, "data-testid": "dialog-ok", className: "min-w-[100px]", children: "Ok" })] })] })] }) }));
}
//# sourceMappingURL=LinkEditorDialog.js.map