import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useEffect, useState, useRef } from "react";
import { Star, ChevronDown, X, Pencil, Check, Ban } from "lucide-react";
import { DropdownMenu, DropdownMenuContent, DropdownMenuTrigger, DropdownMenuItem, DropdownMenuSeparator, } from "../../components/ui/dropdown-menu";
import { Button } from "../../components/ui/button";
import { Input } from "../../components/ui/input";
import { Tooltip, TooltipContent, TooltipTrigger, } from "../../components/ui/tooltip";
import * as favouritesService from "../services/favouritesService";
import { toast } from "sonner";
import { getAbsoluteIconUrl } from "../utils";
import { cn } from "../../lib/utils";
export function FavoritesControls({ itemDescriptor, editContext, }) {
    // Favorites state
    const [isFavorite, setIsFavorite] = useState(false);
    const [favorites, setFavorites] = useState([]);
    const [favoritesLoading, setFavoritesLoading] = useState(false);
    const [togglingFavorite, setTogglingFavorite] = useState(false);
    const [favoriteItems, setFavoriteItems] = useState(new Map());
    // Edit state
    const [editingFavorite, setEditingFavorite] = useState(null);
    const [editName, setEditName] = useState("");
    const [dropdownOpen, setDropdownOpen] = useState(false);
    const editInputRef = useRef(null);
    const favoritesLoadSequence = useRef(0);
    const applyFavoritesList = async (favoritesList) => {
        const sortedFavorites = [...favoritesList].sort((a, b) => b.priority - a.priority);
        setFavorites(sortedFavorites);
        // Load item details for each favorite
        const itemMap = new Map();
        for (const favorite of sortedFavorites) {
            try {
                const item = await editContext?.itemsRepository.getItem({
                    id: favorite.itemId,
                    language: favorite.language,
                    version: 0,
                });
                if (item) {
                    itemMap.set(`${favorite.itemId}-${favorite.language}`, item);
                }
            }
            catch (error) {
                // Silently ignore item loading errors
            }
        }
        setFavoriteItems(itemMap);
    };
    // Check if current page is favorite by looking at the favorites list
    const checkFavoriteStatus = () => {
        if (!itemDescriptor) {
            setIsFavorite(false);
            return;
        }
        const isCurrentItemFavorite = favorites.some((favorite) => favorite.itemId === itemDescriptor.id &&
            favorite.language === itemDescriptor.language);
        setIsFavorite(isCurrentItemFavorite);
    };
    // Toggle favorite status
    const toggleFavorite = async (e) => {
        // Prevent event propagation if event is provided
        if (e) {
            e.preventDefault();
            e.stopPropagation();
        }
        if (!itemDescriptor) {
            toast.error("No item selected");
            return;
        }
        if (togglingFavorite)
            return;
        setTogglingFavorite(true);
        try {
            // Calculate priority for new favorite: use minimum priority - 1 to ensure it appears at the end
            // Since favorites are sorted by priority descending, lower priority = appears later
            let priority = 0;
            if (favorites.length > 0) {
                const minPriority = Math.min(...favorites.map((f) => f.priority));
                priority = minPriority - 1;
                // Ensure priority doesn't go too negative (though negative is fine for sorting)
            }
            const result = await favouritesService.toggleFavorite({
                itemId: itemDescriptor.id,
                language: itemDescriptor.language,
                priority: priority,
            });
            if (result.type === "success" && result.data) {
                // Refresh shared lists and then apply the authoritative toggle result.
                await refreshFavoriteLists();
                setIsFavorite(result.data.isFavorite);
                toast.success(result.data.isFavorite
                    ? "Added to favorites"
                    : "Removed from favorites");
            }
            else {
                toast.error("Failed to toggle favorite");
            }
        }
        catch (error) {
            console.error("Error toggling favorite:", error);
            toast.error("Failed to toggle favorite");
        }
        finally {
            setTogglingFavorite(false);
        }
    };
    // Load all favorites
    const loadFavorites = async () => {
        const sequence = ++favoritesLoadSequence.current;
        setFavoritesLoading(true);
        try {
            const result = await favouritesService.getAllFavorites();
            if (sequence !== favoritesLoadSequence.current)
                return;
            if (result.type === "success" && result.data) {
                await applyFavoritesList(result.data);
            }
        }
        catch (error) {
            // Silently ignore favorites loading errors
        }
        finally {
            if (sequence === favoritesLoadSequence.current) {
                setFavoritesLoading(false);
            }
        }
    };
    // Navigate to favorite item
    const navigateToFavorite = async (favorite) => {
        editContext?.loadItem({
            id: favorite.itemId,
            language: favorite.language,
            version: 0, // Use latest version
        });
    };
    // Remove a specific favorite item
    const removeFavorite = async (favorite, event) => {
        event.stopPropagation(); // Prevent navigation when clicking remove button
        try {
            const result = await favouritesService.toggleFavorite({
                itemId: favorite.itemId,
                language: favorite.language,
                priority: favorite.priority,
            });
            if (result.type === "success" && result.data) {
                // Refresh shared lists and then apply the authoritative toggle result.
                await refreshFavoriteLists();
                if (itemDescriptor?.id === favorite.itemId &&
                    itemDescriptor?.language === favorite.language) {
                    setIsFavorite(result.data.isFavorite);
                }
            }
            else {
                toast.error("Failed to remove favorite");
            }
        }
        catch (error) {
            toast.error("Failed to remove favorite");
        }
    };
    // Start editing a favorite name
    const startEditing = (favorite, event) => {
        event.stopPropagation(); // Prevent navigation when clicking edit button
        event.preventDefault(); // Prevent dropdown from closing
        setDropdownOpen(true);
        const itemKey = `${favorite.itemId}-${favorite.language}`;
        const item = favoriteItems.get(itemKey);
        // Use custom name if set, otherwise use item name as initial value
        setEditName(favorite.name || item?.name || "");
        setEditingFavorite(itemKey);
        // Focus input after state update
        requestAnimationFrame(() => {
            editInputRef.current?.focus();
            editInputRef.current?.select();
        });
    };
    // Cancel editing
    const cancelEditing = () => {
        setEditingFavorite(null);
        setEditName("");
        // Optionally close dropdown when canceling
        // setDropdownOpen(false);
    };
    // Save edited name
    const saveEditedName = async (favorite) => {
        try {
            const result = await favouritesService.updateFavoriteName({
                itemId: favorite.itemId,
                language: favorite.language,
                name: editName.trim() || "",
            });
            if (result.type === "success" && result.data) {
                toast.success("Favorite name updated");
                setEditingFavorite(null);
                setEditName("");
                await refreshFavoriteLists();
                // Optionally close dropdown after saving
                // setDropdownOpen(false);
            }
            else {
                toast.error("Failed to update favorite name");
            }
        }
        catch (error) {
            toast.error("Failed to update favorite name");
        }
    };
    // Handle key press in edit input
    const handleEditKeyDown = (event, favorite) => {
        if (event.key === "Enter") {
            saveEditedName(favorite);
        }
        else if (event.key === "Escape") {
            cancelEditing();
        }
    };
    useEffect(() => {
        loadFavorites();
    }, [itemDescriptor]);
    const refreshFavoriteLists = async () => {
        await Promise.all([loadFavorites(), editContext.loadFavorites()]);
    };
    useEffect(() => {
        applyFavoritesList(editContext.favorites);
    }, [editContext.favorites]);
    // Check favorite status whenever favorites list or itemDescriptor changes
    useEffect(() => {
        checkFavoriteStatus();
    }, [favorites, itemDescriptor]);
    // Maintain focus on input when editing
    useEffect(() => {
        if (editingFavorite && editInputRef.current) {
            // Use requestAnimationFrame to ensure DOM is updated
            requestAnimationFrame(() => {
                if (editInputRef.current) {
                    editInputRef.current.focus();
                    editInputRef.current.select();
                }
            });
        }
    }, [editingFavorite]);
    return (_jsxs("div", { className: "group flex items-center", children: [_jsxs(Tooltip, { children: [_jsx(TooltipTrigger, { asChild: true, children: _jsx(Button, { variant: "ghost", size: "sm", onClick: (e) => toggleFavorite(e), disabled: !itemDescriptor || togglingFavorite, className: "h-8 w-7", "data-testid": "toggle-favorite-button", children: isFavorite ? (_jsx(Star, { "data-testid": "favorite-star-filled", className: "fill-highlight-100 text-highlight-100", size: 16, strokeWidth: 1, absoluteStrokeWidth: true })) : (_jsx(Star, { "data-testid": "favorite-star-outline", className: "text-neutral-grey-50", size: 16, strokeWidth: 1, absoluteStrokeWidth: true })) }) }), _jsx(TooltipContent, { children: !itemDescriptor
                            ? "No item selected"
                            : isFavorite
                                ? "Remove from favorites"
                                : "Add to favorites" })] }), _jsxs(DropdownMenu, { open: dropdownOpen, onOpenChange: (open) => {
                    // Keep dropdown open when editing
                    if (!open && editingFavorite) {
                        // Prevent closing when editing - force it to stay open
                        setDropdownOpen(true);
                        return;
                    }
                    setDropdownOpen(open);
                }, children: [_jsxs(Tooltip, { children: [_jsx(TooltipTrigger, { asChild: true, children: _jsx(DropdownMenuTrigger, { asChild: true, children: _jsx(Button, { variant: "ghost", size: "sm", className: "h-8 w-5 p-0", "data-testid": "favorites-dropdown-trigger", children: _jsx(ChevronDown, { size: 16, strokeWidth: 1, absoluteStrokeWidth: true }) }) }) }), _jsx(TooltipContent, { children: "View favorites" })] }), _jsxs(DropdownMenuContent, { align: "start", className: "w-80 text-xs", "data-testid": "favorites-dropdown-content", children: [_jsx("div", { className: "px-2 py-1.5 text-xs font-medium", children: "Favorites" }), _jsx(DropdownMenuSeparator, {}), favoritesLoading ? (_jsx("div", { className: "text-neutral-grey-50 px-2 py-4 text-center text-xs", children: "Loading favorites..." })) : favorites.length === 0 ? (_jsx("div", { className: "text-neutral-grey-50 px-2 py-4 text-center text-xs", children: "No favorites yet" })) : (_jsx("div", { className: "max-h-60 overflow-auto", children: favorites.map((favorite, index) => {
                                    const itemKey = `${favorite.itemId}-${favorite.language}`;
                                    const item = favoriteItems.get(itemKey);
                                    const isEditing = editingFavorite === itemKey;
                                    const displayName = favorite.name || item?.name || favorite.itemId;
                                    const keyboardShortcut = index < 9 ? `Ctrl+Alt+${index + 1}` : null;
                                    const isDeleted = !item;
                                    if (isEditing) {
                                        return (_jsxs("div", { className: "flex items-start gap-2 px-2 py-2", onMouseDown: (e) => e.preventDefault(), children: [item?.icon && (_jsx("img", { src: getAbsoluteIconUrl(item.icon), alt: "", className: "mt-0.5 h-4 w-4 shrink-0" })), _jsx("div", { className: "flex min-w-0 flex-1 flex-col", children: _jsxs("div", { className: "flex w-full items-center gap-1", children: [_jsx(Input, { ref: editInputRef, value: editName, onChange: (e) => setEditName(e.target.value), onKeyDown: (e) => handleEditKeyDown(e, favorite), autoFocus: true, className: "h-6 flex-1 text-xs" }), _jsx(Button, { variant: "ghost", size: "sm", onClick: (e) => {
                                                                    e.preventDefault();
                                                                    saveEditedName(favorite);
                                                                }, className: "h-6 w-6 p-0", children: _jsx(Check, { strokeWidth: 1, className: "h-3 w-3" }) }), _jsx(Button, { variant: "ghost", size: "sm", onClick: (e) => {
                                                                    e.preventDefault();
                                                                    cancelEditing();
                                                                }, className: "h-6 w-6 p-0", children: _jsx(X, { strokeWidth: 1, className: "h-3 w-3" }) })] }) })] }, itemKey));
                                    }
                                    return (_jsxs(DropdownMenuItem, { onClick: () => !isDeleted && navigateToFavorite(favorite), className: cn("flex items-start gap-2 px-2 py-2", isDeleted && "cursor-default opacity-60"), children: [isDeleted ? (_jsx(Ban, { className: "text-neutral-grey-50 mt-0.5 h-4 w-4 shrink-0", strokeWidth: 1 })) : item?.icon ? (_jsx("img", { src: getAbsoluteIconUrl(item.icon), alt: "", className: "mt-0.5 h-4 w-4 shrink-0" })) : null, _jsxs("div", { className: "flex min-w-0 flex-1 flex-col", children: [_jsxs("div", { className: "flex items-center gap-2", children: [_jsx("div", { className: cn("truncate text-xs font-medium", isDeleted && "text-neutral-grey-50"), children: displayName }), keyboardShortcut && !isDeleted && (_jsxs("kbd", { className: "bg-muted text-muted-foreground pointer-events-none inline-flex h-4 items-center gap-0.5 rounded border px-1 font-mono text-[9px] font-medium opacity-100 select-none", children: [_jsx("span", { className: "text-[9px]", children: "Ctrl" }), _jsx("span", { className: "text-[9px]", children: "+" }), _jsx("span", { className: "text-[9px]", children: "Alt" }), _jsx("span", { className: "text-[9px]", children: "+" }), _jsx("span", { className: "text-[9px]", children: index + 1 })] }))] }), _jsx("div", { className: cn("truncate text-xs", isDeleted
                                                            ? "text-neutral-grey-50"
                                                            : "text-neutral-grey-50"), children: isDeleted
                                                            ? "Item no longer exists"
                                                            : item?.path || favorite.language })] }), _jsxs("div", { className: "ml-2 flex items-center gap-1", children: [!isDeleted && (_jsxs(Tooltip, { children: [_jsx(TooltipTrigger, { asChild: true, children: _jsx(Button, { variant: "ghost", size: "sm", onClick: (e) => startEditing(favorite, e), className: "h-6 w-6 shrink-0 p-0 opacity-70 hover:opacity-100", children: _jsx(Pencil, { strokeWidth: 1, className: "h-3 w-3" }) }) }), _jsx(TooltipContent, { children: "Edit name" })] })), _jsxs(Tooltip, { children: [_jsx(TooltipTrigger, { asChild: true, children: _jsx(Button, { variant: "ghost", size: "sm", onClick: (e) => removeFavorite(favorite, e), className: "h-6 w-6 shrink-0 p-0 opacity-70 hover:opacity-100", children: _jsx(X, { strokeWidth: 1, className: "h-3 w-3" }) }) }), _jsx(TooltipContent, { children: "Remove from favorites" })] })] })] }, itemKey));
                                }) }))] })] })] }));
}
//# sourceMappingURL=FavoritesControls.js.map