import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useCallback, useEffect, useState } from "react";
import { useEditContext } from "../client/editContext";
import { Lightbulb, MessageSquare, X } from "lucide-react";
import { LanguageSelector } from "../../components/ui/LanguageSelector";
import { HomeListBadge, HomeListIcon, homeListContainerClass, homeListRowClass, } from "../ui/HomeListRow";
import { Spinner } from "../ui/Spinner";
import { isLatestFeedbackRefreshMessage, LATEST_FEEDBACK_TAKE, loadLatestFeedbackItems, } from "./latestFeedbackData";
import { openCommentsFeedback } from "./openCommentsFeedback";
import { formatDate } from "../utils";
import { getCommentScrollIntoViewTarget, getSuggestedEditScrollIntoViewTarget, } from "./feedbackScrollTarget";
export function LatestFeedback() {
    const editContext = useEditContext();
    const [items, setItems] = useState([]);
    const [isLoading, setIsLoading] = useState(false);
    const [error, setError] = useState(null);
    const [selectedLanguage, setSelectedLanguage] = useState(undefined);
    const load = useCallback(async () => {
        let cancelled = false;
        setIsLoading(true);
        setError(null);
        try {
            const latest = await loadLatestFeedbackItems(LATEST_FEEDBACK_TAKE, selectedLanguage);
            if (!cancelled)
                setItems(latest);
        }
        catch (e) {
            if (!cancelled)
                setError(e?.message || "Failed to load latest items");
        }
        finally {
            if (!cancelled)
                setIsLoading(false);
        }
        return () => {
            cancelled = true;
        };
    }, [selectedLanguage]);
    useEffect(() => {
        let disposed;
        (async () => {
            disposed = await load();
        })();
        return () => {
            try {
                disposed?.();
            }
            catch { }
        };
    }, [load]);
    useEffect(() => {
        const dispose = editContext?.addSocketMessageListener?.((message) => {
            try {
                if (isLatestFeedbackRefreshMessage(message?.type)) {
                    void load();
                }
            }
            catch { }
        });
        return () => {
            try {
                dispose?.();
            }
            catch { }
        };
    }, [editContext?.addSocketMessageListener, load]);
    const onOpenItem = async (item) => {
        try {
            const mainId = item.kind === "comment" ? item.mainItemId : item.mainItemId;
            const lang = item.kind === "comment" ? item.language : item.mainItemLanguage;
            const ver = item.kind === "comment" ? item.version : item.mainItemVersion;
            await editContext?.loadItem({ id: mainId, language: lang, version: ver });
            editContext?.setSelectedComment(item.kind === "comment" ? item : undefined);
            editContext?.setSelectedSuggestedEdit(item.kind === "suggestion" ? item : undefined);
            if (item.kind === "comment") {
                editContext?.setScrollIntoView(getCommentScrollIntoViewTarget(item));
            }
            else {
                editContext?.setScrollIntoView(getSuggestedEditScrollIntoViewTarget(item));
            }
            editContext?.switchWorkspace("editor");
            openCommentsFeedback(editContext);
        }
        catch { }
    };
    const Row = ({ item }) => {
        const isComment = item.kind === "comment";
        const created = item.created
            ? new Date(item.created)
            : undefined;
        const dateText = created ? formatDate(created) : "";
        const comment = isComment ? item : undefined;
        const pageName = isComment
            ? comment?.mainItemName ||
                (comment?.relatedItems || []).find((ri) => ri.itemId === comment?.mainItemId)?.itemName
            : item.mainItemName;
        const componentName = isComment
            ? comment?.itemName
            : item.itemName;
        const fieldName = isComment ? comment?.fieldName : undefined;
        const user = item.authorDisplayName || item.author || "";
        const label = isComment ? "Comment" : "Suggestion";
        const title = pageName || componentName || fieldName || label;
        const contextSegments = [
            pageName ? componentName : undefined,
            fieldName || (item.kind === "suggestion" ? item.fieldId : undefined),
            user,
        ].filter((x) => !!x && x.length > 0);
        return (_jsxs("button", { className: homeListRowClass, onClick: () => onOpenItem(item), children: [_jsx(HomeListIcon, { "aria-label": label, title: label, children: isComment ? (_jsx(MessageSquare, { className: "h-4 w-4", strokeWidth: 1.5 })) : (_jsx(Lightbulb, { className: "h-4 w-4", strokeWidth: 1.5 })) }), _jsxs("div", { className: "min-w-0 flex-1", children: [_jsx("div", { className: "text-neutral-grey-100 truncate text-sm font-medium", children: title }), _jsx("div", { className: "text-neutral-grey-50 mt-0.5 truncate text-xs", children: contextSegments.map((segment, idx) => (_jsxs("span", { children: [idx > 0 ? " > " : "", segment] }, `${segment}-${idx}`))) })] }), _jsx("div", { className: "text-neutral-grey-50 hidden shrink-0 text-xs md:block", children: dateText }), _jsx(HomeListBadge, { className: "bg-neutral-grey-5 text-neutral-grey-100 md:hidden", children: label })] }));
    };
    return (_jsxs("div", { className: "h-full overflow-auto", children: [_jsx("div", { className: "border-border-default flex items-center gap-1 border-b px-4 py-3", children: selectedLanguage ? (_jsxs("div", { className: "bg-neutral-grey-5 inline-flex items-center rounded-full pr-0.5", children: [_jsx(LanguageSelector, { selectedLanguage: selectedLanguage, onLanguageSelected: (language) => setSelectedLanguage(language.languageCode), showAllLanguages: true, triggerVariant: "ghost" }), _jsx("button", { type: "button", "aria-label": "Clear language filter", title: "Clear language filter", className: "text-neutral-grey-50 hover:bg-neutral-grey-10 hover:text-neutral-grey-100 ml-0.5 inline-flex h-5 w-5 cursor-pointer items-center justify-center rounded-full", onClick: () => setSelectedLanguage(undefined), children: _jsx(X, { className: "h-3 w-3", strokeWidth: 2 }) })] })) : (_jsx(LanguageSelector, { selectedLanguage: selectedLanguage, onLanguageSelected: (language) => setSelectedLanguage(language.languageCode), showAllLanguages: true, triggerVariant: "ghost", placeholder: "Filter by language" })) }), isLoading && (_jsxs("div", { className: "text-neutral-grey-50 flex items-center gap-2 p-4 text-xs", children: [_jsx(Spinner, { size: "sm" }), "Loading..."] })), error && _jsx("div", { className: "text-feedback-red p-4 text-xs", children: error }), !isLoading && !error && items.length === 0 && (_jsx("div", { className: "text-neutral-grey-50 p-12 text-center text-sm", children: "No recent activity" })), _jsx("div", { className: homeListContainerClass, children: items.map((it) => (_jsx(Row, { item: it }, `${it.kind}-${it.id}`))) })] }));
}
//# sourceMappingURL=LatestFeedback.js.map