"use client";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import * as React from "react";
import { useState } from "react";
import { useEditContext, useFieldsEditContext } from "../client/editContext";
import { Popover, PopoverContent, PopoverTrigger, } from "../../components/ui/popover";
import { formatDate } from "../utils";
import { Button } from "../../components/ui/button";
import { deleteSuggestedEdit, createOrUpdateSuggestedEdit, } from "../services/suggestedEditsService";
import { cleanupPendingSuggestedEditOperations, waitForPendingSuggestedEditSave, } from "../client/operations";
import { Check, Brush, GalleryVertical, Lightbulb, X } from "lucide-react";
import { DeleteIcon } from "../../components/ui/delete-icon";
import { DiffView } from "./DiffView";
import { SimpleIconButton } from "../ui/SimpleIconButton";
import { createPatch, applyPatch } from "diff";
import { cn } from "../../lib/utils";
import { SuggestionCommentThread } from "./SuggestionCommentThread";
import { FeedbackContextHeader, getSuggestionContextSegments, } from "./FeedbackCard";
import { getFeedbackAvatarClassName } from "./feedbackAvatar";
import { Avatar } from "../../components/ui/avatar";
import { useResolvedUser } from "../services/userResolution";
export function SuggestionDisplayPopover({ suggestion, children, onSuggestionUpdated, }) {
    const editContext = useEditContext();
    const fieldsContext = useFieldsEditContext();
    const resolvedAuthor = useResolvedUser(suggestion.author, {
        fullName: suggestion.authorDisplayName,
    });
    const [isOpen, setIsOpen] = useState(false);
    const [deleteConfirm, setDeleteConfirm] = useState(false);
    const [isApplying, setIsApplying] = useState(false);
    const [item, setItem] = useState(null);
    const [patchPossible, setPatchPossible] = useState(true);
    const [patchWarning, setPatchWarning] = useState("");
    const [ignoreFormatting, setIgnoreFormatting] = useState(true);
    const [clipUnchanged, setClipUnchanged] = useState(true);
    const canDelete = suggestion.author === editContext?.user?.name &&
        suggestion.status !== "applied";
    const canApply = suggestion.status !== "applied" && !editContext?.readonly;
    const suggestionComments = React.useMemo(() => (editContext?.comments || []).filter((comment) => comment.suggestedEditId === suggestion.id), [editContext?.comments, suggestion.id]);
    // Load the full item when popover opens
    React.useEffect(() => {
        if (isOpen && editContext?.itemsRepository && suggestion.itemId) {
            editContext.itemsRepository
                .getItem({
                id: suggestion.itemId,
                language: suggestion.mainItemLanguage,
                version: suggestion.mainItemVersion,
            })
                .then((loadedItem) => {
                setItem(loadedItem);
                checkAndComputePatch(loadedItem);
            })
                .catch((err) => {
                console.error("Error loading item:", err);
            });
        }
    }, [isOpen, suggestion, editContext?.itemsRepository]);
    // Check if the patch can be applied cleanly
    const checkAndComputePatch = async (loadedItem) => {
        const field = loadedItem?.fields?.find((f) => f.id === suggestion.fieldId);
        if (!field)
            return;
        const currentValue = field.rawValue || "";
        const patch = createPatch("field", suggestion.oldValue, suggestion.newValue);
        const patchedCandidate = applyPatch(currentValue, patch);
        if (patchedCandidate === false || typeof patchedCandidate !== "string") {
            setPatchPossible(false);
            setPatchWarning("Patch cannot be applied cleanly to current field value.");
        }
        else {
            setPatchPossible(true);
            setPatchWarning("");
        }
    };
    const handleDelete = async () => {
        if (!deleteConfirm) {
            setDeleteConfirm(true);
            return;
        }
        try {
            await deleteSuggestedEdit(suggestion);
            // Clean up pending operations to prevent race conditions
            cleanupPendingSuggestedEditOperations(suggestion, editContext?.user);
            // Immediately update local state to reflect deletion
            if (editContext?.setSuggestedEdits && editContext?.suggestedEdits) {
                const updatedEdits = editContext.suggestedEdits.filter((e) => e.id !== suggestion.id);
                editContext.setSuggestedEdits(updatedEdits);
            }
            if (editContext?.setComments && editContext?.comments) {
                editContext.setComments(editContext.comments.filter((comment) => comment.suggestedEditId !== suggestion.id));
            }
        }
        catch (error) {
            console.error("Failed to delete suggested edit:", error);
        }
        finally {
            setIsOpen(false);
            onSuggestionUpdated?.();
        }
    };
    const runInEditMode = (action, actionDescription) => {
        if (!editContext || isApplying)
            return;
        if (editContext.mode === "edit") {
            void action();
            return;
        }
        editContext.confirm({
            header: "Switch to Edit Mode?",
            message: `Applying suggestions requires edit mode. Switch to edit mode to ${actionDescription}?`,
            acceptLabel: "Switch and apply",
            rejectLabel: "Cancel",
            accept: async () => {
                editContext.setMode("edit");
                await action();
            },
        });
    };
    const applySuggestionPatch = async () => {
        if (!patchPossible || !editContext || isApplying)
            return;
        setIsApplying(true);
        try {
            await waitForPendingSuggestedEditSave(suggestion);
            // Recalculate the patch immediately before applying
            const field = item?.fields?.find((f) => f.id === suggestion.fieldId);
            if (!field)
                return;
            const currentValue = field.rawValue || "";
            const patch = createPatch("field", suggestion.oldValue, suggestion.newValue);
            const patchedCandidate = applyPatch(currentValue, patch);
            if (patchedCandidate === false || typeof patchedCandidate !== "string") {
                setPatchWarning("Patch cannot be applied cleanly to current field value.");
                return;
            }
            await editContext.operations.editField({
                field: {
                    fieldId: suggestion.fieldId,
                    item: {
                        id: suggestion.itemId,
                        language: suggestion.mainItemLanguage,
                        version: suggestion.mainItemVersion,
                    },
                },
                value: patchedCandidate,
                rawValue: patchedCandidate,
                forceMode: "edit",
                refresh: "immediate",
            });
            // Update the suggestion status to "applied"
            const updatedSuggestion = { ...suggestion, status: "applied" };
            await createOrUpdateSuggestedEdit(updatedSuggestion);
            onSuggestionUpdated?.();
            setIsOpen(false);
        }
        finally {
            setIsApplying(false);
        }
    };
    const replaceCompletely = async () => {
        if (!editContext || isApplying)
            return;
        setIsApplying(true);
        try {
            await waitForPendingSuggestedEditSave(suggestion);
            await editContext.operations.editField({
                field: {
                    fieldId: suggestion.fieldId,
                    item: {
                        id: suggestion.itemId,
                        language: suggestion.mainItemLanguage,
                        version: suggestion.mainItemVersion,
                    },
                },
                value: suggestion.newValue,
                rawValue: suggestion.newValue,
                forceMode: "edit",
                refresh: "immediate",
            });
            const updatedSuggestion = { ...suggestion, status: "applied" };
            await createOrUpdateSuggestedEdit(updatedSuggestion);
            onSuggestionUpdated?.();
            setIsOpen(false);
        }
        finally {
            setIsApplying(false);
        }
    };
    const handleApplyPatch = () => {
        if (!patchPossible || !editContext || isApplying)
            return;
        runInEditMode(applySuggestionPatch, "apply this suggestion");
    };
    const handleReplaceCompletely = () => {
        if (!editContext || isApplying)
            return;
        runInEditMode(replaceCompletely, "replace the field content");
    };
    const fieldName = item && item.fields
        ? item.fields.find((f) => f.id === suggestion.fieldId)?.name || undefined
        : undefined;
    const contextSegments = getSuggestionContextSegments(suggestion, editContext?.currentItemDescriptor?.name, item ? item.name : undefined, fieldName);
    const renderDiffToggleButtons = () => {
        return (_jsxs("div", { className: "mb-2 flex gap-2", children: [_jsx(SimpleIconButton, { icon: _jsx(Brush, { size: 14, className: "p-0.5", strokeWidth: 1 }), label: "Ignore Formatting", onClick: () => setIgnoreFormatting((prev) => !prev), className: cn("text-neutral-grey-50", ignoreFormatting ? "bg-neutral-grey-10" : "") }), _jsx(SimpleIconButton, { icon: _jsx(GalleryVertical, { size: 14, className: "p-0.5", strokeWidth: 1 }), label: "Clip", onClick: () => setClipUnchanged((prev) => !prev), className: cn("text-neutral-grey-50", clipUnchanged ? "bg-neutral-grey-10" : "") })] }));
    };
    return (_jsxs(Popover, { open: isOpen, onOpenChange: (open) => {
            setIsOpen(open);
            if (!open) {
                setDeleteConfirm(false);
                setPatchWarning("");
            }
        }, enableIframeClickDetection: true, children: [_jsx(PopoverTrigger, { asChild: true, children: children }), _jsx(PopoverContent, { className: "border-border-default w-[420px] overflow-hidden rounded-2xl border bg-white p-0 shadow-xl", side: "bottom", align: "start", children: _jsxs("div", { className: "flex max-h-[560px] flex-col", children: [_jsxs("div", { className: "border-border-default flex h-10 shrink-0 items-center border-b px-4", children: [_jsx("div", { className: "text-neutral-grey-100 text-base font-semibold", children: "Suggestion" }), _jsxs("div", { className: "ml-auto flex items-center gap-1", children: [_jsx(Lightbulb, { className: "text-feedback-orange h-4 w-4 shrink-0" }), canApply && patchPossible && suggestion.status !== "applied" && (_jsx(Button, { variant: "ghost", size: "sm", onClick: handleApplyPatch, disabled: isApplying, className: "text-neutral-grey-100 h-8 w-8 p-0", "aria-label": "Apply suggestion", children: _jsx(Check, { size: 16, strokeWidth: 2 }) })), suggestion.status === "applied" && (_jsx("div", { className: "flex h-8 w-8 items-center justify-center", children: _jsx(Check, { size: 16, strokeWidth: 2, className: "text-feedback-green" }) })), canDelete && (_jsx(Button, { variant: "ghost", size: "sm", onClick: handleDelete, className: `text-neutral-grey-50 hover:bg-neutral-grey-5 hover:text-neutral-grey-50 h-8 w-8 p-0 ${deleteConfirm ? "!text-neutral-grey-100" : ""}`, "aria-label": "Delete suggestion", children: _jsx(DeleteIcon, { size: "lg" }) })), _jsx(Button, { variant: "ghost", size: "sm", onClick: () => setIsOpen(false), className: "text-neutral-grey-50 hover:bg-neutral-grey-5 hover:text-neutral-grey-50 h-8 w-8 p-0", "aria-label": "Close suggestion", "data-testid": "close-suggestion-popover", children: _jsx(X, { size: 16, strokeWidth: 2 }) })] })] }), _jsx(FeedbackContextHeader, { segments: contextSegments }), _jsxs("div", { className: "min-h-0 flex-1 overflow-y-auto p-4", children: [_jsxs("div", { className: "mb-3 flex items-start gap-3", children: [_jsx(Avatar, { src: resolvedAuthor.avatarUrl, name: suggestion.authorDisplayName || suggestion.author, size: "sm", fallbackClassName: getFeedbackAvatarClassName(suggestion), className: "text-[11px] font-semibold", title: suggestion.author }), _jsxs("div", { children: [_jsx("div", { className: "text-neutral-grey-100 text-sm font-semibold", children: suggestion.authorDisplayName || suggestion.author }), _jsx("div", { className: "text-neutral-grey-50 text-xs", children: suggestion.created
                                                        ? formatDate(new Date(suggestion.created))
                                                        : "" })] })] }), suggestion.status === "applied" && (_jsxs("div", { className: "text-feedback-green text-xs font-medium", children: ["\u2713 Applied", " ", suggestion.updatedBy ? `by ${suggestion.updatedBy}` : "", suggestion.updated
                                            ? ` on ${formatDate(new Date(suggestion.updated))}`
                                            : ""] })), renderDiffToggleButtons(), _jsxs("div", { className: "text-sm", children: [_jsx(DiffView, { oldText: suggestion.oldValue, newText: suggestion.newValue, ignoreFormatting: ignoreFormatting, clipUnchanged: clipUnchanged, clipThreshold: 50, clipContext: 10 }), canApply && patchWarning && (_jsxs("div", { className: "text-feedback-red mt-2 text-xs", children: [patchWarning, _jsx("button", { className: "hover:text-feedback-red ml-2 cursor-pointer underline", onClick: handleReplaceCompletely, disabled: isApplying, children: "Click here to replace the field content completely." })] }))] }), canApply && !patchPossible && suggestion.status !== "applied" && (_jsx("div", { className: "border-t pt-3", children: _jsx(Button, { size: "sm", onClick: handleReplaceCompletely, disabled: isApplying, className: "w-full", children: isApplying ? "Applying..." : "Replace Field Content" }) })), (!editContext?.readonly || suggestionComments.length > 0) && (_jsx("div", { className: "border-t pt-3", children: _jsx(SuggestionCommentThread, { suggestion: suggestion, comments: suggestionComments, compact: true, constrainHeight: true }) })), deleteConfirm && (_jsxs("div", { className: "border-t pt-3", children: [_jsx("div", { className: "text-feedback-red mb-2 text-sm", children: "Are you sure you want to delete this suggestion?" }), _jsxs("div", { className: "flex gap-2", children: [_jsx(Button, { variant: "outline", size: "sm", onClick: () => setDeleteConfirm(false), children: "Cancel" }), _jsx(Button, { variant: "destructive", size: "sm", onClick: handleDelete, children: "Delete" })] })] })), !deleteConfirm && !editContext?.configuration?.forceFullscreen && (_jsx("div", { className: "border-t pt-3", children: _jsx(Button, { variant: "outline", size: "sm", onClick: () => {
                                            setIsOpen(false);
                                            // Exit fullscreen mode if active
                                            if (editContext?.fullscreen) {
                                                editContext.setFullscreen(false);
                                            }
                                            // Focus on the field and select the item
                                            if (suggestion.fieldId) {
                                                fieldsContext?.setFocusedField({
                                                    fieldId: suggestion.fieldId,
                                                    item: {
                                                        id: suggestion.itemId,
                                                        language: suggestion.mainItemLanguage,
                                                        version: suggestion.mainItemVersion,
                                                    },
                                                }, false);
                                                editContext?.select?.([suggestion.itemId]);
                                            }
                                            // Open the feedback sidebar
                                            editContext?.openSidebar("feedback");
                                        }, className: "w-full", children: "View in Feedback Panel" }) }))] })] }) })] }));
}
//# sourceMappingURL=SuggestionDisplayPopover.js.map