import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useEffect, useRef, useState } from "react";
import { flushSync } from "react-dom";
import { useEditContext, useFieldsEditContext } from "../client/editContext";
import { deleteSuggestedEdit, createOrUpdateSuggestedEdit, } from "../services/suggestedEditsService";
import { cleanupPendingSuggestedEditOperations, waitForPendingSuggestedEditSave, } from "../client/operations";
import { formatDate } from "../utils";
import { SimpleIconButton } from "../ui/SimpleIconButton";
import { Popover, PopoverContent, PopoverTrigger, } from "../../components/ui/popover";
import { DiffView } from "./DiffView";
// Import lucide icons (adjust names as needed)
import { Brush, Check, GalleryVertical, MoreHorizontal } from "lucide-react";
import { DeleteIcon } from "../../components/ui/delete-icon";
// Import patch functions from the diff library.
import { createPatch, applyPatch } from "diff";
import { cn } from "../../lib/utils";
import { getFeedbackAuthorName, getFeedbackAvatarClassName, } from "./feedbackAvatar";
import { Avatar } from "../../components/ui/avatar";
import { useResolvedUser } from "../services/userResolution";
import { FeedbackCardFrame, getSuggestionContextSegments, } from "./FeedbackCard";
export function SuggestedEditComponent({ edit, resolvedAuthorName, children, }) {
    const editContext = useEditContext();
    const fieldsContext = useFieldsEditContext();
    const ref = useRef(null);
    const [item, setItem] = useState(null);
    const [patchPossible, setPatchPossible] = useState(true);
    const [patchWarning, setPatchWarning] = useState("");
    const [applied, setApplied] = useState(false);
    const [isApplying, setIsApplying] = useState(false);
    const [ignoreFormatting, setIgnoreFormatting] = useState(true);
    const [clipUnchanged, setClipUnchanged] = useState(true);
    const canApply = edit.status !== "applied" && !editContext?.readonly && !isApplying;
    // Load the full item from the repository.
    useEffect(() => {
        if (editContext?.itemsRepository &&
            edit.itemId &&
            edit.mainItemLanguage &&
            edit.mainItemVersion !== undefined) {
            editContext.itemsRepository
                .getItem({
                id: edit.itemId,
                language: edit.mainItemLanguage,
                version: edit.mainItemVersion,
            })
                .then((loadedItem) => {
                setItem(loadedItem);
                // When the item loads, check if the patch is applicable.
                checkAndComputePatch(loadedItem);
            })
                .catch((err) => {
                console.error("Error loading item:", err);
            });
        }
    }, [
        edit.itemId,
        edit.mainItemLanguage,
        edit.mainItemVersion,
        editContext?.itemsRepository,
    ]);
    // Determine if this suggested edit is selected based on the focused field.
    const isSelected = fieldsContext?.focusedField &&
        !editContext?.selectedComment &&
        fieldsContext.focusedField.fieldId === edit.fieldId &&
        fieldsContext.focusedField.item.id === edit.itemId;
    useEffect(() => {
        if (isSelected && ref.current) {
            ref.current.scrollIntoView({ behavior: "smooth", block: "nearest" });
        }
    }, [isSelected]);
    // When a suggested edit is clicked, update the focused field and select the item.
    function handleSelectSuggestedEdit() {
        editContext?.setSelectedComment(undefined);
        if (edit.fieldId) {
            fieldsContext?.setFocusedField({
                fieldId: edit.fieldId,
                item: {
                    id: edit.itemId,
                    language: edit.mainItemLanguage,
                    version: edit.mainItemVersion,
                },
            }, false);
            // Also select the item.
            editContext?.select?.([edit.itemId]);
        }
    }
    // Render contextual info by retrieving item and field names from the loaded item.
    const fieldName = item && item.fields
        ? item.fields.find((f) => f.id === edit.fieldId)?.name || undefined
        : undefined;
    const contextSegments = getSuggestionContextSegments(edit, editContext?.currentItemDescriptor?.name, item ? item.name : undefined, fieldName);
    // Allow deletion only if the current user is the author.
    const canDelete = edit.author === editContext?.user?.name;
    const authorName = getFeedbackAuthorName(edit, resolvedAuthorName);
    const resolvedAuthor = useResolvedUser(edit.author, {
        fullName: edit.authorDisplayName,
    });
    const handleDelete = async () => {
        try {
            await deleteSuggestedEdit(edit);
            cleanupPendingSuggestedEditOperations(edit, editContext?.user);
            if (editContext?.setSuggestedEdits && editContext?.suggestedEdits) {
                const updatedEdits = editContext.suggestedEdits.filter((e) => e.id !== edit.id);
                editContext.setSuggestedEdits(updatedEdits);
            }
            if (editContext?.setComments && editContext?.comments) {
                editContext.setComments(editContext.comments.filter((comment) => comment.suggestedEditId !== edit.id));
            }
        }
        catch (error) {
            console.error("Failed to delete suggested edit:", error);
        }
    };
    // Render the header with author info, creation date, and control buttons.
    const renderHeader = () => {
        const hasActions = (canApply && !applied && patchPossible) || canDelete;
        return (_jsxs("div", { className: "mb-3 flex items-start gap-3", children: [_jsx(Avatar, { src: resolvedAuthor.avatarUrl, name: authorName, size: "sm", fallbackClassName: getFeedbackAvatarClassName(edit), className: "text-[11px] font-semibold", title: edit.author }), _jsx("div", { className: "min-w-0 flex-1", children: _jsxs("div", { className: "flex min-h-7 min-w-0 items-center gap-2", children: [_jsx("span", { className: "text-neutral-grey-100 truncate text-sm font-semibold", title: edit.author, children: authorName }), _jsx("span", { className: "text-neutral-grey-50 shrink-0 text-xs", children: edit.created ? formatDate(new Date(edit.created)) : "" })] }) }), applied && (_jsx("span", { className: "text-feedback-green inline-flex h-7 w-7 shrink-0 items-center justify-center", title: edit.updated
                        ? `Applied by ${edit.updatedBy} (${formatDate(new Date(edit.updated))})`
                        : undefined, children: _jsx(Check, { className: "h-4 w-4", strokeWidth: 2 }) })), hasActions && (_jsxs(Popover, { children: [_jsx(PopoverTrigger, { asChild: true, children: _jsx("button", { type: "button", className: "text-neutral-grey-50 hover:bg-neutral-grey-5 -mr-1 inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full", "aria-label": "Suggestion actions", onClick: (e) => e.stopPropagation(), children: _jsx(MoreHorizontal, { className: "h-4 w-4", strokeWidth: 2 }) }) }), _jsxs(PopoverContent, { className: "w-44 p-1", align: "end", children: [canApply && !applied && patchPossible && (_jsxs("button", { type: "button", className: "hover:bg-neutral-grey-5 flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-sm", onClick: (e) => {
                                        e.stopPropagation();
                                        handleApplyPatch();
                                    }, children: [_jsx(Check, { className: "h-4 w-4", strokeWidth: 1.5 }), "Apply"] })), canDelete && (_jsxs("button", { type: "button", className: "hover:bg-neutral-grey-5 flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-sm", onClick: (e) => {
                                        e.stopPropagation();
                                        handleDelete();
                                    }, children: [_jsx(DeleteIcon, { size: "lg" }), "Delete"] }))] })] }))] }));
    };
    // Render toggle buttons using SimpleIconButtons.
    const renderDiffToggleButtons = () => {
        return (_jsxs("div", { className: "mb-2 flex gap-2", children: [_jsx(SimpleIconButton, { icon: _jsx(Brush, { size: 14, className: "p-0.5" }), 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" }), label: "Clip", onClick: () => setClipUnchanged((prev) => !prev), className: cn("text-neutral-grey-50", clipUnchanged ? "bg-neutral-grey-10" : "") })] }));
    };
    // Helper: Check if the patch is applicable to the current field value.
    async function checkAndComputePatch(loadedItem) {
        const field = loadedItem?.fields?.find((f) => f.id === edit.fieldId);
        if (!field)
            return;
        const currentValue = field.rawValue || "";
        const patch = createPatch("field", edit.oldValue, edit.newValue);
        const patchedCandidate = applyPatch(currentValue, patch);
        if (patchedCandidate === false || typeof patchedCandidate !== "string") {
            setPatchPossible(false);
            setPatchWarning("Patch cannot be applied cleanly.");
        }
        else {
            setPatchPossible(true);
            setPatchWarning("");
        }
    }
    const runInEditMode = (action, actionDescription) => {
        if (!editContext)
            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 () => {
                flushSync(() => {
                    editContext.setMode("edit");
                });
                await action();
            },
        });
    };
    // Handler for applying the patch using editContext.operations.editField.
    async function applySuggestedPatch() {
        if (!patchPossible || isApplying)
            return;
        if (!editContext)
            return;
        setIsApplying(true);
        try {
            await waitForPendingSuggestedEditSave(edit);
            // Recalculate the patch immediately before applying
            const field = item?.fields?.find((f) => f.id === edit.fieldId);
            if (!field)
                return;
            const currentValue = field.rawValue || "";
            const patch = createPatch("field", edit.oldValue, edit.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: edit.fieldId,
                    item: {
                        id: edit.itemId,
                        language: edit.mainItemLanguage,
                        version: edit.mainItemVersion,
                    },
                },
                value: patchedCandidate,
                rawValue: patchedCandidate,
                forceMode: "edit",
                refresh: "immediate",
            });
            // Update the suggestion status to "Applied" and persist the update.
            const updatedEdit = { ...edit, status: "applied" };
            await createOrUpdateSuggestedEdit(updatedEdit);
            setApplied(true);
            setPatchWarning("");
        }
        finally {
            setIsApplying(false);
        }
    }
    // Handler for replacing the field content completely using editContext.operations.editField.
    async function replaceFieldCompletely() {
        if (!editContext || isApplying)
            return;
        setIsApplying(true);
        try {
            await waitForPendingSuggestedEditSave(edit);
            await editContext.operations.editField({
                field: {
                    fieldId: edit.fieldId,
                    item: {
                        id: edit.itemId,
                        language: edit.mainItemLanguage,
                        version: edit.mainItemVersion,
                    },
                },
                value: edit.newValue,
                rawValue: edit.newValue,
                forceMode: "edit",
                refresh: "immediate",
            });
            const updatedEdit = { ...edit, status: "applied" };
            await createOrUpdateSuggestedEdit(updatedEdit);
            setApplied(true);
            setPatchWarning("");
        }
        finally {
            setIsApplying(false);
        }
    }
    function handleApplyPatch() {
        if (!patchPossible || !editContext)
            return;
        runInEditMode(applySuggestedPatch, "apply this suggestion");
    }
    function handleReplaceCompletely() {
        if (!editContext)
            return;
        runInEditMode(replaceFieldCompletely, "replace the field content");
    }
    return (_jsx("div", { ref: ref, children: _jsxs(FeedbackCardFrame, { contextSegments: contextSegments, selected: !!isSelected, testId: "suggested-edit", className: "cursor-pointer", onClick: handleSelectSuggestedEdit, children: [renderHeader(), renderDiffToggleButtons(), _jsxs("div", { className: "text-neutral-grey-100 text-sm whitespace-pre-wrap", children: [_jsx(DiffView, { oldText: edit.oldValue, newText: edit.newValue, ignoreFormatting: ignoreFormatting, clipUnchanged: clipUnchanged, clipThreshold: 50, clipContext: 10 }), canApply && patchWarning && (_jsxs("div", { className: "text-feedback-red mt-1 text-xs", children: [patchWarning, _jsx("a", { className: "ml-2 cursor-pointer underline", onClick: handleReplaceCompletely, children: "Click here to replace the field content." })] }))] }), children && (_jsx("div", { className: "border-border-default mt-4 border-t pt-3", children: children }))] }) }));
}
//# sourceMappingURL=SuggestedEdit.js.map