"use client";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useEffect, useState } from "react";
import { ChevronDown } from "lucide-react";
import { DeleteIcon } from "../../components/ui/delete-icon";
import { useEditContext } from "../client/editContext";
import { ScrollingContentTree } from "../ScrollingContentTree";
import { getLookupSources } from "../services/editService";
import { cn } from "../../lib/utils";
import ItemSearch from "../ui/ItemSearch";
import { normalizeGuid } from "../utils";
import { Popover, PopoverContent, PopoverTrigger, } from "../../components/ui/popover";
export function InternalLinkFieldEditor({ field, readOnly, }) {
    const editContext = useEditContext();
    const [link, setLink] = useState();
    const [showTree, setShowTree] = useState(false);
    const [rootItemIds, setRootItemIds] = useState([]);
    const [defaultExpandedItemId, setDefaultExpandedItemId] = useState();
    useEffect(() => {
        if (!field.value) {
            setLink(undefined);
            return;
        }
        setLink({
            url: field.value.url,
            target: field.value.target,
            targetItemName: field.value.targetItemName,
            targetItemLongId: field.value.targetItemLongId,
            type: field.value.type,
            itemId: 
            // Prefer short id if provided by backend; otherwise derive from long id
            field.value.targetItemId ??
                field.value.targetItemLongId?.split("/").pop(),
            queryString: field.value.queryString,
        });
    }, [field]);
    if (!editContext)
        return;
    // Helper function to normalize GUID formats for comparison
    const normalizeKey = (key) => {
        return key.toLowerCase().replace(/[{}]/g, "");
    };
    useEffect(() => {
        const loadLookupSources = async () => {
            const response = await getLookupSources(field);
            if (response.items.length > 0) {
                setRootItemIds(response.items.map((x) => x.id));
            }
            else
                setRootItemIds(["11111111-1111-1111-1111-111111111111"]);
        };
        loadLookupSources();
    }, [
        field.descriptor.fieldId +
            field.descriptor.item.id +
            field.descriptor.item.language +
            field.descriptor.item.version,
    ]);
    // When no value is selected, and the current item is a child of one of the root items,
    // expand the tree to the current item without selecting it.
    useEffect(() => {
        const computeDefaultExpansion = async () => {
            if (!editContext?.currentItemDescriptor)
                return;
            // Only compute when no link target is selected
            if (link?.itemId)
                return;
            if (!rootItemIds || rootItemIds.length === 0)
                return;
            const normalizedRootIds = new Set(rootItemIds.map((id) => normalizeKey(id)));
            // Prefer the current item from context if available; otherwise fetch it
            const currentItem = editContext.item
                ? editContext.item
                : await editContext.itemsRepository.getItem({
                    id: editContext.currentItemDescriptor.id,
                    language: editContext.currentItemDescriptor.language ?? "en",
                    version: editContext.currentItemDescriptor.version,
                });
            if (!currentItem?.idPath)
                return;
            const pathIds = currentItem.idPath
                .split("/")
                .map((s) => s.trim())
                .filter(Boolean)
                .map((s) => normalizeKey(s));
            const isUnderAnyRoot = pathIds.some((id) => normalizedRootIds.has(id));
            if (isUnderAnyRoot) {
                setDefaultExpandedItemId(normalizeKey(currentItem.id));
            }
            else {
                setDefaultExpandedItemId(undefined);
            }
        };
        computeDefaultExpansion();
        // Recompute when root items change or when the context item changes
    }, [
        editContext?.currentItemDescriptor?.id,
        editContext?.currentItemDescriptor?.language,
        editContext?.currentItemDescriptor?.version,
        rootItemIds.join("|"),
        link?.itemId,
    ]);
    // If we have an item id but no name (some backends don't return targetItemName),
    // fetch the item to backfill the display name.
    useEffect(() => {
        let cancelled = false;
        const backfillName = async () => {
            if (!editContext)
                return;
            if (!link?.itemId)
                return;
            if (link?.targetItemName)
                return;
            try {
                const item = await editContext.itemsRepository.getItem({
                    id: normalizeKey(link.itemId),
                    language: editContext.currentItemDescriptor?.language ?? "en",
                    version: 0,
                });
                if (!cancelled && item?.name) {
                    setLink((prev) => prev ? { ...prev, targetItemName: item.name } : prev);
                }
            }
            catch { }
        };
        backfillName();
        return () => {
            cancelled = true;
        };
    }, [
        editContext,
        editContext?.currentItemDescriptor?.language,
        link?.itemId,
        link?.targetItemName,
    ]);
    return (_jsx("div", { className: "relative", children: _jsxs(Popover, { open: showTree, onOpenChange: setShowTree, children: [_jsx(PopoverTrigger, { asChild: true, disabled: readOnly, children: _jsxs("div", { className: cn("justiy-between focus-shadow bg-neutral-grey-5 flex cursor-pointer justify-between rounded-sm border p-1.5 text-xs", readOnly ? "bg-neutral-grey-5 cursor-default" : ""), children: [link?.targetItemName ? (_jsx("span", { children: link.targetItemName })) : (_jsx("span", { children: "\u00A0" })), !readOnly && (_jsx(ChevronDown, { strokeWidth: 1, className: `h-4 w-4 transition-transform duration-200 ${showTree ? "rotate-180" : "rotate-0"}` }))] }) }), !readOnly && (_jsxs(PopoverContent, { className: "w-96 p-0", align: "start", side: "bottom", children: [_jsx("div", { className: "border-border-default border-b bg-white p-2", children: _jsx(ItemSearch, { rootItemIds: rootItemIds.map((x) => normalizeGuid(x)), autoFocus: true, itemSelected: (item) => {
                                    const itemId = normalizeGuid(item.id);
                                    // Optimistically update UI label to reflect selection immediately
                                    setLink((prev) => ({
                                        ...(prev || { type: "internal" }),
                                        itemId,
                                        targetItemName: item.name ?? (prev?.targetItemName || ""),
                                        url: undefined,
                                        targetItemLongId: undefined,
                                    }));
                                    setShowTree(false);
                                    editContext?.operations.editField({
                                        field: field.descriptor,
                                        rawValue: itemId,
                                    });
                                } }) }), _jsx("button", { className: "bg-neutral-grey-5 hover:bg-neutral-grey-5 w-full cursor-pointer rounded border-b p-1 px-4 text-left text-xs", onClick: () => {
                                setShowTree(false);
                                // Optimistically clear local link state
                                setLink(undefined);
                                editContext?.operations.editField({
                                    field: field.descriptor,
                                    rawValue: null,
                                });
                            }, children: _jsxs("div", { className: "flex items-center gap-2", children: [_jsx(DeleteIcon, { size: "lg" }), " Clear"] }) }), _jsx("div", { className: "relative h-64 border-x border-b", children: _jsx(ScrollingContentTree, { selectedItemId: link?.itemId ? normalizeKey(link.itemId) : undefined, rootItemIds: rootItemIds, expandedItemId: link?.itemId
                                    ? normalizeKey(link.itemId)
                                    : defaultExpandedItemId, onSelectionChange: (nodes) => {
                                    setShowTree(false);
                                    const selected = nodes[0];
                                    const selectedNode = selected?.id;
                                    // Optimistically update UI label and id
                                    if (selectedNode) {
                                        setLink((prev) => ({
                                            ...(prev || { type: "internal" }),
                                            itemId: selectedNode,
                                            targetItemName: selected?.displayName ||
                                                selected?.name ||
                                                prev?.targetItemName,
                                            url: undefined,
                                            targetItemLongId: undefined,
                                        }));
                                    }
                                    editContext?.operations.editField({
                                        field: field.descriptor,
                                        rawValue: selectedNode
                                            ? normalizeGuid(selectedNode)
                                            : undefined,
                                    });
                                } }) })] }))] }) }));
}
//# sourceMappingURL=InternalLinkFieldEditor.js.map