import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useState, useMemo, useCallback } from "react";
import { Button } from "../../../components/ui/button";
import { Input } from "../../../components/ui/input";
import { Checkbox } from "../../../components/ui/checkbox";
import { Search, Component as ComponentIcon, X, Layers, Target, } from "lucide-react";
import { useEditContext } from "../../client/editContext";
import { getInsertOptionsForCurrentSelection, getAllInsertOptions, } from "../../utils/insertOptions";
import { cn } from "../../../lib/utils";
/**
 * ComponentTypeSelectorInline - Inline component for selecting component types
 *
 * This is rendered directly inside the AgentTerminal rather than as a modal dialog.
 * Displays available component types from the current page context
 * and allows the user to select one or more.
 *
 * Supports two modes:
 * - "placeholder": Shows only component types valid for available placeholders
 * - "all": Shows all component types registered for the current page/site
 */
export function ComponentTypeSelectorInline({ onClose, onCancel, title = "Select Component Types", description = "Choose one or more component types from the available options.", parameters = {}, }) {
    const editContext = useEditContext();
    const [searchTerm, setSearchTerm] = useState("");
    const [selectedIds, setSelectedIds] = useState(new Set());
    // Mode state - default to parameter value or "placeholder"
    const [mode, setMode] = useState(parameters.mode || "placeholder");
    const { allowMultiple = true, minSelections, maxSelections } = parameters;
    // Get available component types based on mode
    const availableOptions = useMemo(() => {
        // If availableTypes was provided by the backend (for "all" mode), use those
        if (mode === "all" &&
            parameters.availableTypes &&
            parameters.availableTypes.length > 0) {
            // Convert ComponentTypeSelection to InsertOption format
            return parameters.availableTypes.map((t) => ({
                typeId: t.typeId,
                name: t.name,
                icon: t.icon,
                group: t.group,
            }));
        }
        if (!editContext)
            return [];
        if (mode === "all") {
            // Get ALL component types from ALL placeholders (fallback if backend didn't provide them)
            return getAllInsertOptions(editContext);
        }
        else {
            // Get only component types valid for selected/available placeholders
            return getInsertOptionsForCurrentSelection(editContext);
        }
    }, [editContext, mode, parameters.availableTypes]);
    // Filter options based on search term
    const filteredOptions = useMemo(() => {
        if (!searchTerm.trim())
            return availableOptions;
        const term = searchTerm.toLowerCase();
        return availableOptions.filter((option) => option.name.toLowerCase().includes(term) ||
            option.group?.toLowerCase().includes(term));
    }, [availableOptions, searchTerm]);
    // Group options by their group property
    const groupedOptions = useMemo(() => {
        const groups = new Map();
        for (const option of filteredOptions) {
            const groupName = option.group || "Other";
            if (!groups.has(groupName)) {
                groups.set(groupName, []);
            }
            groups.get(groupName).push(option);
        }
        // Sort groups alphabetically, but put "Other" at the end
        const sortedGroups = Array.from(groups.entries()).sort((a, b) => {
            if (a[0] === "Other")
                return 1;
            if (b[0] === "Other")
                return -1;
            return a[0].localeCompare(b[0]);
        });
        return sortedGroups;
    }, [filteredOptions]);
    // Handle selection toggle
    const toggleSelection = useCallback((typeId) => {
        setSelectedIds((prev) => {
            const newSet = new Set(prev);
            if (newSet.has(typeId)) {
                newSet.delete(typeId);
            }
            else {
                if (!allowMultiple) {
                    // Single selection mode - clear previous selection
                    newSet.clear();
                }
                else if (maxSelections && newSet.size >= maxSelections) {
                    // Max selections reached - don't add
                    return prev;
                }
                newSet.add(typeId);
            }
            return newSet;
        });
    }, [allowMultiple, maxSelections]);
    // Handle select all
    const handleSelectAll = useCallback(() => {
        if (!allowMultiple)
            return;
        const allIds = filteredOptions.map((o) => o.typeId);
        const idsToSelect = maxSelections ? allIds.slice(0, maxSelections) : allIds;
        setSelectedIds(new Set(idsToSelect));
    }, [filteredOptions, allowMultiple, maxSelections]);
    // Handle clear all
    const handleClearAll = useCallback(() => {
        setSelectedIds(new Set());
    }, []);
    // Validate selection count
    const isValidSelection = useMemo(() => {
        const count = selectedIds.size;
        if (minSelections && count < minSelections)
            return false;
        if (maxSelections && count > maxSelections)
            return false;
        return count > 0;
    }, [selectedIds, minSelections, maxSelections]);
    // Handle confirm
    const handleConfirm = useCallback(() => {
        const selectedOptions = availableOptions.filter((o) => selectedIds.has(o.typeId));
        const result = selectedOptions.map((o) => ({
            typeId: o.typeId,
            name: o.name,
            icon: o.icon,
            group: o.group,
        }));
        onClose(result);
    }, [availableOptions, selectedIds, onClose]);
    return (_jsxs("div", { className: "border-t border-gray-200 bg-gradient-to-b from-blue-50/50 to-white", children: [_jsxs("div", { className: "flex items-center justify-between border-b border-gray-100 px-4 py-3", children: [_jsxs("div", { children: [_jsx("h3", { className: "text-sm font-semibold text-gray-900", children: title }), description && (_jsx("p", { className: "mt-0.5 text-xs text-gray-500", children: description }))] }), _jsx("button", { onClick: onCancel, className: "rounded-full p-1 transition-colors hover:bg-gray-100", "aria-label": "Cancel", children: _jsx(X, { size: 16, className: "text-gray-400" }) })] }), _jsxs("div", { className: "flex items-center gap-1 border-b border-gray-100 bg-gray-50/50 px-4 py-2", children: [_jsx("span", { className: "mr-2 text-[11px] text-gray-500", children: "Show:" }), _jsxs("button", { onClick: () => {
                            setMode("placeholder");
                            setSelectedIds(new Set()); // Clear selection when mode changes
                        }, className: cn("flex items-center gap-1.5 rounded px-2.5 py-1 text-[11px] font-medium transition-colors", mode === "placeholder"
                            ? "border border-blue-200 bg-blue-100 text-blue-700"
                            : "border border-gray-200 bg-white text-gray-600 hover:bg-gray-50"), title: "Show only component types valid for currently available placeholders", children: [_jsx(Target, { size: 12 }), "Available"] }), _jsxs("button", { onClick: () => {
                            setMode("all");
                            setSelectedIds(new Set()); // Clear selection when mode changes
                        }, className: cn("flex items-center gap-1.5 rounded px-2.5 py-1 text-[11px] font-medium transition-colors", mode === "all"
                            ? "border border-blue-200 bg-blue-100 text-blue-700"
                            : "border border-gray-200 bg-white text-gray-600 hover:bg-gray-50"), title: "Show all component types from the page schema", children: [_jsx(Layers, { size: 12 }), "Schema"] })] }), _jsxs("div", { className: "flex items-center gap-2 border-b border-gray-100 px-4 py-2", children: [_jsxs("div", { className: "relative flex-1", children: [_jsx(Search, { className: "absolute top-1/2 left-2.5 -translate-y-1/2 text-gray-400", size: 14, strokeWidth: 1.5 }), _jsx(Input, { placeholder: "Search components...", value: searchTerm, onChange: (e) => setSearchTerm(e.target.value), className: "h-8 pl-8 text-xs" })] }), allowMultiple && (_jsxs("div", { className: "flex items-center gap-1", children: [_jsx(Button, { variant: "ghost", size: "sm", onClick: handleSelectAll, disabled: filteredOptions.length === 0, className: "h-8 px-2 text-xs", children: "All" }), _jsx(Button, { variant: "ghost", size: "sm", onClick: handleClearAll, disabled: selectedIds.size === 0, className: "h-8 px-2 text-xs", children: "Clear" })] }))] }), _jsxs("div", { className: "flex items-center justify-between bg-gray-50/50 px-4 py-1.5 text-[11px] text-gray-400", children: [_jsxs("span", { children: [selectedIds.size, " selected", minSelections && ` (min: ${minSelections})`, maxSelections && ` (max: ${maxSelections})`] }), _jsxs("span", { children: [filteredOptions.length, " available"] })] }), _jsx("div", { className: "max-h-[240px] overflow-auto", children: availableOptions.length === 0 ? (_jsxs("div", { className: "flex flex-col items-center justify-center py-8 text-gray-400", children: [_jsx(ComponentIcon, { size: 32, strokeWidth: 1, className: "mb-2 opacity-50" }), _jsxs("p", { className: "px-4 text-center text-xs", children: ["No component types available.", _jsx("br", {}), "Make sure a page with placeholders is loaded."] })] })) : filteredOptions.length === 0 ? (_jsxs("div", { className: "flex flex-col items-center justify-center py-8 text-gray-400", children: [_jsx(Search, { size: 32, strokeWidth: 1, className: "mb-2 opacity-50" }), _jsx("p", { className: "text-xs", children: "No matching components found." })] })) : (_jsx("div", { className: "p-2", children: groupedOptions.map(([groupName, options]) => (_jsxs("div", { className: "mb-3 last:mb-0", children: [_jsx("div", { className: "px-2 py-1 text-[10px] font-semibold tracking-wider text-gray-400 uppercase", children: groupName }), _jsx("div", { className: "space-y-0.5", children: options.map((option) => (_jsxs("div", { className: `flex cursor-pointer items-center gap-2 rounded px-2 py-1.5 transition-colors ${selectedIds.has(option.typeId)
                                        ? "border border-blue-200 bg-blue-50"
                                        : "border border-transparent hover:bg-gray-50"}`, onClick: () => toggleSelection(option.typeId), children: [_jsx(Checkbox, { checked: selectedIds.has(option.typeId), onCheckedChange: () => toggleSelection(option.typeId), className: "pointer-events-none h-3.5 w-3.5" }), option.icon && (_jsx("img", { src: option.icon, alt: "", className: "h-4 w-4 object-contain", onError: (e) => {
                                                e.target.style.display =
                                                    "none";
                                            } })), _jsx("span", { className: "flex-1 text-xs font-medium text-gray-700", children: option.name })] }, option.typeId))) })] }, groupName))) })) }), _jsxs("div", { className: "flex items-center justify-end gap-2 border-t border-gray-100 bg-gray-50/50 px-4 py-3", children: [_jsx(Button, { variant: "outline", size: "sm", onClick: onCancel, className: "h-8 text-xs", children: "Cancel" }), _jsx(Button, { size: "sm", onClick: handleConfirm, disabled: !isValidSelection, className: "h-8 text-xs", children: selectedIds.size === 0
                            ? "Select"
                            : selectedIds.size === 1
                                ? "Select 1 Component"
                                : `Select ${selectedIds.size} Components` })] })] }));
}
export default ComponentTypeSelectorInline;
//# sourceMappingURL=ComponentTypeSelectorInline.js.map