import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { Button } from "../../components/ui/button";
import { useState, useEffect, useMemo } from "react";
import { Dialog, DialogContent } from "../../components/ui/dialog";
import { StyledDialogTitle } from "../../components/ui/styled-dialog-title";
import DialogButtons from "./DialogButtons";
import ContentTree from "../ContentTree";
import ItemSearch from "./ItemSearch";
import { Search, Layout, Clock } from "lucide-react";
import { Splitter } from "./Splitter";
import { localStorageService } from "../services/localStorageService";
const TEMPLATES_ROOT_ID = "{3C1715FE-6A13-4FCF-845F-DE308BA9741D}"; // /sitecore/templates
const TEMPLATE_TEMPLATE_ID = "AB86861A-6030-46C5-B394-E8F99E8B87DB"; // Template item template ID
// Helper function to normalize GUID for comparison (removes braces and converts to uppercase)
const normalizeGuid = (guid) => {
    if (!guid)
        return "";
    return guid.replace(/[{}]/g, "").toUpperCase();
};
const RECENT_TEMPLATES_STORAGE_KEY = "editor.recentChangeTemplates";
const MAX_RECENT_TEMPLATES = 10;
export function TemplateSelectorDialog(props) {
    if (!props)
        return null;
    const [selectedItem, setSelectedItem] = useState();
    const [expandIdPath, setExpandIdPath] = useState();
    const [recentTemplates, setRecentTemplates] = useState([]);
    const [recentItems, setRecentItems] = useState([]);
    const [isLoadingRecent, setIsLoadingRecent] = useState(false);
    useEffect(() => {
        const stored = localStorageService.getItem(RECENT_TEMPLATES_STORAGE_KEY);
        if (stored) {
            const templateIds = Array.isArray(stored)
                ? stored.filter((id) => typeof id === "string")
                : [];
            const uniqueTemplates = [...new Set(templateIds)];
            setRecentTemplates(uniqueTemplates);
        }
    }, []);
    useEffect(() => {
        const loadRecentItems = async () => {
            if (recentTemplates.length === 0) {
                setRecentItems([]);
                return;
            }
            setIsLoadingRecent(true);
            try {
                const items = await props.editContext.itemsRepository.getItems(recentTemplates.map((id) => ({
                    id,
                    version: 0,
                    language: props.currentItem.language,
                })));
                if (items) {
                    // Filter to only valid templates and remove duplicates
                    // Also exclude the current item's template from recent list
                    const currentTemplateId = normalizeGuid(props.currentItem.templateId);
                    const validTemplates = items.filter((item) => normalizeGuid(item?.templateId) === TEMPLATE_TEMPLATE_ID &&
                        normalizeGuid(item.id) !== currentTemplateId);
                    const uniqueItems = validTemplates.filter((item, index, self) => self.findIndex((i) => i.id === item.id) === index);
                    setRecentItems(uniqueItems);
                }
            }
            catch (error) {
                console.error("Failed to load recent templates:", error);
                setRecentItems([]);
            }
            finally {
                setIsLoadingRecent(false);
            }
        };
        loadRecentItems();
    }, [
        recentTemplates,
        props.currentItem.language,
        props.currentItem.templateId,
        props.editContext.itemsRepository,
    ]);
    const handleOk = () => {
        props.onClose?.(selectedItem ?? null);
    };
    const handleCancel = () => {
        props.onClose?.(null);
    };
    const handleItemSelected = async (item) => {
        // Verify it's a valid template before selecting
        const fullItem = await props.editContext.itemsRepository.getItem(item);
        if (normalizeGuid(fullItem?.templateId) === TEMPLATE_TEMPLATE_ID) {
            setSelectedItem({
                id: item.id,
                version: 0,
                language: "en",
            });
            // Use idPath from search result or fullItem to expand tree to selected item
            const idPath = item.idPath || fullItem?.idPath;
            if (idPath) {
                setExpandIdPath(idPath);
            }
        }
    };
    const handleRecentTemplateSelected = (template) => {
        setSelectedItem({
            id: template.id,
            version: 0,
            language: template.language || "en",
        });
    };
    const recentPanel = useMemo(() => ({
        name: "recent",
        defaultSize: 320,
        className: "bg-neutral-grey-5/30",
        content: (_jsxs("div", { className: "flex h-full flex-col overflow-hidden border-r", children: [_jsxs("div", { className: "bg-neutral-grey-5/50 flex items-center gap-2 border-b px-4 py-3", children: [_jsx(Clock, { className: "text-muted-foreground h-4 w-4" }), _jsx("span", { className: "text-neutral-grey-50 text-xs font-medium tracking-wider", children: "Recent" })] }), _jsx("div", { className: "flex-1 overflow-auto p-4", children: isLoadingRecent ? (_jsx("div", { className: "text-muted-foreground flex items-center justify-center p-8 text-sm", children: "Loading..." })) : recentItems.length === 0 ? (_jsxs("div", { className: "text-muted-foreground flex flex-col items-center justify-center p-8 text-center text-sm", children: [_jsx(Clock, { className: "mb-2 h-8 w-8 opacity-20" }), _jsx("p", { children: "No recent templates" })] })) : (_jsx("div", { className: "space-y-2", children: recentItems.map((template) => (_jsxs("div", { className: `group flex cursor-pointer items-center gap-3 rounded-lg border p-3 transition-all ${selectedItem?.id === template.id
                                ? "border-primary/30 bg-primary/5 ring-primary/20 shadow-sm ring-1"
                                : "hover:border-primary/20 border-border-default bg-white hover:shadow-sm"}`, onClick: () => handleRecentTemplateSelected(template), children: [template.icon && (_jsx("img", { src: template.icon, alt: "", className: "h-5 w-5 shrink-0 opacity-70 group-hover:opacity-100", onDragStart: (e) => e.preventDefault() })), _jsx("span", { className: "text-neutral-grey-100 flex-1 truncate text-sm font-medium", children: template.name })] }, template.id))) })) })] })),
    }), [isLoadingRecent, recentItems, selectedItem]);
    const browsePanel = useMemo(() => ({
        name: "browse",
        defaultSize: "auto",
        content: (_jsxs("div", { className: "flex h-full flex-col overflow-hidden bg-white", children: [_jsxs("div", { className: "bg-neutral-grey-5/50 flex items-center gap-2 border-b px-6 py-3", children: [_jsx(Search, { className: "text-muted-foreground h-4 w-4" }), _jsx("span", { className: "text-neutral-grey-50 text-xs font-medium tracking-wider", children: "Browse All Templates" })] }), _jsxs("div", { className: "flex flex-1 flex-col overflow-hidden p-6", children: [_jsx("div", { className: "mb-4 shrink-0", children: _jsx(ItemSearch, { rootItemIds: [TEMPLATES_ROOT_ID], itemSelected: handleItemSelected, language: props.currentItem.language, autoFocus: true }) }), _jsx("div", { className: "border-border-default bg-neutral-grey-5/20 relative flex-1 overflow-auto rounded-xl border shadow-inner", children: _jsx("div", { className: "p-2", children: _jsx(ContentTree, { language: props.currentItem.language, rootItemIds: [TEMPLATES_ROOT_ID], selectedItemIds: selectedItem?.id ? [selectedItem.id] : [], selectionMode: "single", className: "p-1", expandIdPath: expandIdPath, scrollToSelected: true, onSelectionChange: async (node) => {
                                        if (!node[0]) {
                                            setSelectedItem(null);
                                        }
                                        else {
                                            const item = await props.editContext.itemsRepository.getItem(node[0]);
                                            // Only allow selection of actual templates, not template folders
                                            if (normalizeGuid(item?.templateId) === TEMPLATE_TEMPLATE_ID) {
                                                setSelectedItem({
                                                    id: node[0].id,
                                                    version: 0,
                                                    language: "en",
                                                });
                                            }
                                            else {
                                                setSelectedItem(null);
                                            }
                                        }
                                    }, hideRootNodes: true }) }) })] })] })),
    }), [
        selectedItem,
        expandIdPath,
        props.currentItem.language,
        handleItemSelected,
        props.editContext.itemsRepository,
    ]);
    return (_jsx(Dialog, { open: true, onOpenChange: (open) => {
            if (!open) {
                props.onClose?.(null);
            }
        }, children: _jsxs(DialogContent, { className: "flex flex-col overflow-hidden border-none p-0 shadow-2xl", style: {
                width: "94vw",
                maxWidth: "1200px",
                height: "80vh",
                maxHeight: "800px",
            }, children: [_jsx(StyledDialogTitle, { icon: _jsx(Layout, { strokeWidth: 1 }), title: "Change Template", subtitle: "Select a new template for the current item", headerClassName: "bg-neutral-grey-5/80 backdrop-blur-sm" }), _jsx("div", { className: "flex min-h-0 flex-1 flex-col overflow-hidden", children: _jsx(Splitter, { localStorageKey: "editor.changeTemplateSplitter", panels: [recentPanel, browsePanel] }) }), _jsxs(DialogButtons, { className: "border-t", children: [_jsx(Button, { onClick: handleCancel, variant: "ghost", children: "Cancel" }), _jsx(Button, { onClick: handleOk, variant: "default", disabled: !selectedItem, className: "min-w-[160px] shadow-sm", children: "Change Template" })] })] }) }));
}
//# sourceMappingURL=TemplateSelectorDialog.js.map