"use client";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useEditContext, useEditContextRef } from "../client/editContext";
import { useEffect, useState, useCallback, useRef } from "react";
import { Star, Pencil, Check, X, Trash2, GripVertical, FolderTree, Ban, } from "lucide-react";
import { SimpleToolbar } from "../ui/SimpleToolbar";
import { SimpleIconButton } from "../ui/SimpleIconButton";
import * as favouritesService from "../services/favouritesService";
import { toast } from "sonner";
import { getAbsoluteIconUrl } from "../utils";
import { localStorageService } from "../services/localStorageService";
import { Input } from "../../components/ui/input";
import { Button } from "../../components/ui/button";
import { Tooltip, TooltipContent, TooltipTrigger, } from "../../components/ui/tooltip";
import { cn } from "../../lib/utils";
export function Favorites() {
    const editContext = useEditContext();
    const editContextRef = useEditContextRef();
    const [favorites, setFavorites] = useState([]);
    const [loading, setLoading] = useState(true);
    const [editingId, setEditingId] = useState(null);
    const [editName, setEditName] = useState("");
    const editInputRef = useRef(null);
    const [draggedIndex, setDraggedIndex] = useState(null);
    const [dragOverIndex, setDragOverIndex] = useState(null);
    const [showPaths, setShowPaths] = useState(() => {
        const saved = localStorageService.getString("favorites.showPaths");
        return saved !== null ? saved === "true" : false;
    });
    if (!editContext)
        return null;
    // Persist showPaths to localStorage when it changes
    useEffect(() => {
        localStorageService.setString("favorites.showPaths", String(showPaths));
    }, [showPaths]);
    const currentItemId = editContext.currentItemDescriptor?.id;
    const currentLanguage = editContext.currentItemDescriptor?.language;
    // Load all favorites with item details
    // Use ref to access itemsRepository to avoid re-running when repository reference changes
    const loadFavorites = useCallback(async () => {
        setLoading(true);
        try {
            const result = await favouritesService.getAllFavorites();
            if (result.type === "success" && result.data) {
                // Sort favorites by priority descending (highest priority first)
                const sortedFavorites = result.data.sort((a, b) => b.priority - a.priority);
                // Load item details for each favorite
                const favoritesWithDetails = [];
                for (const favorite of sortedFavorites) {
                    let item = null;
                    try {
                        const loadedItem = await editContextRef.current?.itemsRepository.getItem({
                            id: favorite.itemId,
                            language: favorite.language,
                            version: 0,
                        });
                        item = loadedItem ?? null;
                    }
                    catch {
                        // Silently ignore item loading errors
                    }
                    favoritesWithDetails.push({ favorite, item });
                }
                setFavorites(favoritesWithDetails);
            }
        }
        catch {
            // Silently ignore loading errors
        }
        finally {
            setLoading(false);
        }
    }, [editContextRef]);
    // Load favorites on mount only (not when itemsRepository changes)
    useEffect(() => {
        loadFavorites();
    }, []);
    // Navigate to favorite item
    const navigateToFavorite = useCallback((favorite) => {
        editContext?.loadItem({
            id: favorite.itemId,
            language: favorite.language,
            version: 0,
        });
    }, [editContext]);
    // Remove a favorite
    const removeFavorite = useCallback(async (favorite, event) => {
        event.stopPropagation();
        try {
            const result = await favouritesService.toggleFavorite({
                itemId: favorite.itemId,
                language: favorite.language,
                priority: favorite.priority,
            });
            if (result.type === "success" && result.data) {
                toast.success("Removed from favorites");
                loadFavorites();
            }
            else {
                toast.error("Failed to remove favorite");
            }
        }
        catch {
            toast.error("Failed to remove favorite");
        }
    }, [loadFavorites]);
    // Start editing a favorite name
    const startEditing = useCallback((favorite, item, event) => {
        event.stopPropagation();
        setEditName(favorite.name || item?.name || "");
        setEditingId(`${favorite.itemId}-${favorite.language}`);
        requestAnimationFrame(() => {
            editInputRef.current?.focus();
            editInputRef.current?.select();
        });
    }, []);
    // Cancel editing
    const cancelEditing = useCallback(() => {
        setEditingId(null);
        setEditName("");
    }, []);
    // Save edited name
    const saveEditedName = useCallback(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");
                setEditingId(null);
                setEditName("");
                loadFavorites();
            }
            else {
                toast.error("Failed to update favorite name");
            }
        }
        catch {
            toast.error("Failed to update favorite name");
        }
    }, [editName, loadFavorites]);
    // Handle key press in edit input
    const handleEditKeyDown = useCallback((event, favorite) => {
        if (event.key === "Enter") {
            saveEditedName(favorite);
        }
        else if (event.key === "Escape") {
            cancelEditing();
        }
    }, [saveEditedName, cancelEditing]);
    // Drag and drop handlers for reordering
    const handleDragStart = useCallback((index) => {
        setDraggedIndex(index);
    }, []);
    const handleDragOver = useCallback((e, index) => {
        e.preventDefault();
        setDragOverIndex(index);
    }, []);
    const handleDragEnd = useCallback(() => {
        setDraggedIndex(null);
        setDragOverIndex(null);
    }, []);
    const handleDrop = useCallback(async (e, dropIndex) => {
        e.preventDefault();
        if (draggedIndex === null || draggedIndex === dropIndex) {
            handleDragEnd();
            return;
        }
        // Reorder favorites locally first for immediate UI feedback
        const newFavorites = [...favorites];
        const [draggedItem] = newFavorites.splice(draggedIndex, 1);
        if (!draggedItem) {
            handleDragEnd();
            return;
        }
        newFavorites.splice(dropIndex, 0, draggedItem);
        setFavorites(newFavorites);
        // Note: Backend reordering would require a new API endpoint
        // For now, this is just visual reordering within the session
        handleDragEnd();
    }, [draggedIndex, favorites, handleDragEnd]);
    // Check if current item is a favorite
    const isCurrentItemFavorite = currentItemId && currentLanguage
        ? favorites.some(({ favorite }) => favorite.itemId === currentItemId &&
            favorite.language === currentLanguage)
        : false;
    // Toggle favorite for current item
    const toggleCurrentFavorite = useCallback(async () => {
        if (!currentItemId || !currentLanguage)
            return;
        try {
            // Calculate priority for new favorite
            let priority = 0;
            if (favorites.length > 0) {
                const minPriority = Math.min(...favorites.map(({ favorite }) => favorite.priority));
                priority = minPriority - 1;
            }
            const result = await favouritesService.toggleFavorite({
                itemId: currentItemId,
                language: currentLanguage,
                priority: priority,
            });
            if (result.type === "success" && result.data) {
                if (result.data.isFavorite) {
                    toast.success("Added to favorites");
                }
                else {
                    toast.success("Removed from favorites");
                }
                loadFavorites();
            }
            else {
                toast.error("Failed to toggle favorite");
            }
        }
        catch {
            toast.error("Failed to toggle favorite");
        }
    }, [currentItemId, currentLanguage, favorites, loadFavorites]);
    return (_jsxs("div", { className: "absolute inset-0 flex flex-col", children: [_jsxs(SimpleToolbar, { children: [_jsx(SimpleIconButton, { onClick: toggleCurrentFavorite, disabled: !currentItemId, icon: isCurrentItemFavorite ? (_jsx(Star, { className: "h-4 w-4 fill-current", strokeWidth: 1 })) : (_jsx(Star, { className: "h-4 w-4", strokeWidth: 1 })), label: isCurrentItemFavorite
                            ? "Remove current item from favorites"
                            : "Add current item to favorites", "data-testid": "favorites-toggle-current-button" }), _jsx(SimpleIconButton, { selected: showPaths, onClick: () => setShowPaths(!showPaths), icon: _jsx(FolderTree, { className: "h-4 w-4", strokeWidth: 1 }), label: "Show paths", "data-testid": "favorites-show-paths-button" })] }), _jsx("div", { className: "flex flex-1 flex-col overflow-x-hidden overflow-y-auto text-sm", children: loading ? (_jsx("div", { className: "p-4 text-center text-xs text-gray-500", children: "Loading favorites..." })) : favorites.length === 0 ? (_jsxs("div", { className: "flex flex-col items-center justify-center p-6 text-center", children: [_jsx(Star, { className: "mb-2 h-8 w-8 text-gray-300", strokeWidth: 1 }), _jsx("div", { className: "text-xs font-medium text-gray-500", children: "No favorites yet" }), _jsx("div", { className: "mt-0.5 text-[11px] text-gray-400", children: "Click the star icon to add favorites" })] })) : (_jsx("div", { className: "py-1", children: favorites.map(({ favorite, item }, index) => {
                        const itemKey = `${favorite.itemId}-${favorite.language}`;
                        const isEditing = editingId === itemKey;
                        const displayName = favorite.name || item?.name || favorite.itemId;
                        const isCurrentItem = favorite.itemId === currentItemId &&
                            favorite.language === currentLanguage;
                        const keyboardShortcut = index < 9 ? `Ctrl+Alt+${index + 1}` : null;
                        const isDragging = draggedIndex === index;
                        const isDragOver = dragOverIndex === index;
                        const isDeleted = !item;
                        if (isEditing) {
                            return (_jsxs("div", { className: "flex items-center gap-1.5 bg-gray-50 px-2 py-1", onMouseDown: (e) => e.preventDefault(), children: [item?.icon && (_jsx("img", { src: getAbsoluteIconUrl(item.icon), alt: "", className: "h-3.5 w-3.5 shrink-0" })), _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", placeholder: "Enter custom name..." }), _jsx(Button, { variant: "ghost", size: "sm", onClick: () => saveEditedName(favorite), className: "h-5 w-5 p-0", children: _jsx(Check, { className: "h-3 w-3" }) }), _jsx(Button, { variant: "ghost", size: "sm", onClick: cancelEditing, className: "h-5 w-5 p-0", children: _jsx(X, { className: "h-3 w-3" }) })] }, itemKey));
                        }
                        return (_jsxs("div", { className: cn("group flex gap-1.5 px-2 py-1 transition-colors", showPaths ? "items-start" : "items-center", isDeleted
                                ? "cursor-default opacity-60"
                                : "cursor-pointer hover:bg-gray-50", isCurrentItem &&
                                !isDeleted &&
                                "bg-blue-50 hover:bg-blue-100", isDragging && "opacity-50", isDragOver && "border-t-2 border-blue-400"), onClick: () => !isDeleted && navigateToFavorite(favorite), draggable: !isDeleted, onDragStart: () => !isDeleted && handleDragStart(index), onDragOver: (e) => handleDragOver(e, index), onDragEnd: handleDragEnd, onDrop: (e) => handleDrop(e, index), "data-testid": `favorite-item-${favorite.itemId}`, title: isDeleted ? "This item no longer exists" : undefined, children: [_jsx("div", { className: cn("text-gray-300 transition-opacity", isDeleted
                                        ? "opacity-30"
                                        : "cursor-grab opacity-0 group-hover:opacity-100", showPaths && "mt-0.5"), children: _jsx(GripVertical, { className: "h-3 w-3" }) }), isDeleted ? (_jsx(Ban, { className: cn("h-3.5 w-3.5 shrink-0 text-gray-400", showPaths && "mt-0.5"), strokeWidth: 1 })) : item?.icon ? (_jsx("img", { src: getAbsoluteIconUrl(item.icon), alt: "", className: cn("h-3.5 w-3.5 shrink-0", showPaths && "mt-0.5") })) : (_jsx(Star, { className: cn("h-3.5 w-3.5 shrink-0", showPaths && "mt-0.5", isCurrentItem
                                        ? "fill-blue-400 text-blue-400"
                                        : "text-gray-400"), strokeWidth: 1 })), _jsxs("div", { className: "flex min-w-0 flex-1 flex-col", children: [_jsx("span", { className: cn("truncate text-xs", isDeleted
                                                ? "text-gray-400"
                                                : isCurrentItem
                                                    ? "font-medium text-blue-700"
                                                    : "text-gray-700"), children: displayName }), showPaths && (_jsx("span", { className: cn("truncate text-[10px]", isDeleted ? "text-gray-300" : "text-gray-400"), children: isDeleted
                                                ? "Item no longer exists"
                                                : item?.path || favorite.language }))] }), keyboardShortcut && !isDeleted && (_jsx("kbd", { className: cn("pointer-events-none hidden shrink-0 rounded border bg-gray-100 px-1 font-mono text-[8px] text-gray-400 select-none group-hover:inline", showPaths && "mt-0.5"), children: index + 1 })), _jsxs("div", { className: cn("flex shrink-0 items-center opacity-0 transition-opacity group-hover:opacity-100", showPaths && "mt-0.5"), children: [!isDeleted && (_jsxs(Tooltip, { children: [_jsx(TooltipTrigger, { asChild: true, children: _jsx(Button, { variant: "ghost", size: "sm", onClick: (e) => startEditing(favorite, item, e), className: "h-5 w-5 p-0", children: _jsx(Pencil, { className: "h-2.5 w-2.5" }) }) }), _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-5 w-5 p-0 text-red-500 hover:bg-red-50 hover:text-red-600", children: _jsx(Trash2, { className: "h-2.5 w-2.5" }) }) }), _jsx(TooltipContent, { children: "Remove from favorites" })] })] })] }, itemKey));
                    }) })) })] }));
}
//# sourceMappingURL=Favorites.js.map