import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useEffect, useRef, useState } from "react";
import { useEditContext, useFieldsEditContext } from "../client/editContext";
import { createOrUpdateComment, deleteComment, resolveComment, unresolveComment, } from "../services/reviewsService";
// import { startAgent, StartAgentRequest } from "../services/agentService";
import { openAiAgentForComment } from "./commentAi";
import { useDebouncedCallback } from "use-debounce";
import { CommentView } from "./CommentView";
import { CommentEditor } from "./CommentEditor";
import { toast } from "sonner";
import uuid from "react-uuid";
import { LicenseFeatures, useFeature } from "../../licensing";
export function Comment({ comment, availableTags = [], rootCommentId, }) {
    const editContext = useEditContext();
    const fieldsContext = useFieldsEditContext();
    const canUseAi = useFeature(LicenseFeatures.AI);
    const [isEditing, setIsEditing] = useState(false);
    const [isReplying, setIsReplying] = useState(false);
    const [isSaving, setIsSaving] = useState(false);
    const ref = useRef(null);
    useEffect(() => {
        if (comment.isNew)
            setIsEditing(true);
    }, [comment]);
    const isSelected = comment.id === editContext?.selectedComment?.id;
    useEffect(() => {
        if (isSelected && ref.current) {
            ref.current.scrollIntoView({ behavior: "smooth", block: "nearest" });
        }
    }, [isSelected]);
    const canDelete = !comment.isNew &&
        (comment.author === editContext?.user?.name ||
            editContext?.user?.isAdministrator === true);
    const canEdit = !comment.isNew &&
        !comment.isResolved &&
        comment.author === editContext?.user?.name;
    const canResolve = !comment.isNew && !editContext?.readonly;
    const setCommentsDebounced = useDebouncedCallback(() => {
        if (!editContext?.setComments)
            return;
        editContext.setComments([...editContext.comments]);
    }, 300);
    const handleSave = async (text, tags) => {
        comment.text = text;
        comment.tags = tags.join(",");
        setIsSaving(true);
        try {
            const item = await editContext?.itemsRepository?.getItem({
                id: comment.itemId,
                language: comment.language,
                version: comment.version,
            });
            if (item && comment.fieldId) {
                comment.fieldValue = item.fields.find((f) => f.id === comment.fieldId)?.rawValue;
            }
            const result = await createOrUpdateComment(comment);
            if (result.type === "error" || result.type === "unauthorized") {
                console.error("Failed to save comment:", result);
                if (result.rawDetails) {
                    console.error("Full error details (including stack trace):\n", result.rawDetails);
                }
                toast.error(result.details || result.summary || "Failed to save comment");
                return;
            }
            if (editContext?.setComments) {
                editContext.setComments(editContext.comments.map((c) => c.id === comment.id ? { ...comment, isNew: false } : c));
            }
            setIsEditing(false);
        }
        catch (error) {
            console.error("Failed to save comment:", error);
            toast.error(error instanceof Error ? error.message : "Failed to save comment");
        }
        finally {
            setIsSaving(false);
        }
    };
    const handleCancel = () => {
        if (comment.isNew) {
            if (editContext?.setComments) {
                editContext.setComments([
                    ...editContext.comments.filter((c) => c.id !== comment.id),
                ]);
            }
        }
        else {
            setIsEditing(false);
        }
    };
    const handleDelete = async () => {
        try {
            const result = await deleteComment(comment);
            if (result.type === "error" || result.type === "unauthorized") {
                console.error("Failed to delete comment:", result);
                if (result.rawDetails) {
                    console.error("Full error details (including stack trace):\n", result.rawDetails);
                }
                toast.error(result.details || result.summary || "Failed to delete comment");
            }
            else {
                if (editContext?.setComments) {
                    editContext.setComments(editContext.comments.filter((c) => c.id !== comment.id));
                }
            }
        }
        catch (error) {
            console.error("Failed to delete comment:", error);
            toast.error(error instanceof Error ? error.message : "Failed to delete comment");
        }
    };
    const handleResolve = async () => {
        try {
            const result = await resolveComment(comment);
            if (result.type === "error" || result.type === "unauthorized") {
                console.error("Failed to resolve comment:", result);
                if (result.rawDetails) {
                    console.error("Full error details (including stack trace):\n", result.rawDetails);
                }
                toast.error(result.details || result.summary || "Failed to resolve comment");
            }
        }
        catch (error) {
            console.error("Failed to resolve comment:", error);
            toast.error(error instanceof Error ? error.message : "Failed to resolve comment");
        }
    };
    const handleUnresolve = async () => {
        try {
            const result = await unresolveComment(comment);
            if (result.type === "error" || result.type === "unauthorized") {
                console.error("Failed to unresolve comment:", result);
                if (result.rawDetails) {
                    console.error("Full error details (including stack trace):\n", result.rawDetails);
                }
                toast.error(result.details || result.summary || "Failed to unresolve comment");
            }
        }
        catch (error) {
            console.error("Failed to unresolve comment:", error);
            toast.error(error instanceof Error ? error.message : "Failed to unresolve comment");
        }
    };
    const handleAiAction = async () => openAiAgentForComment(comment, editContext);
    const parentSnippet = comment.parentCommentId && editContext?.comments
        ? (() => {
            const parent = editContext.comments.find((c) => c.id === comment.parentCommentId);
            const source = parent?.text || "";
            const words = source
                .trim()
                .split(/\s+/)
                .filter((w) => w.length > 0)
                .slice(0, 3);
            return words.join(" ");
        })()
        : undefined;
    const buildReplyFrom = (base, text, tags) => {
        const descriptor = editContext.currentItemDescriptor;
        return {
            id: uuid(),
            isNew: false,
            parentCommentId: base.id,
            itemId: base.itemId,
            itemName: base.itemName,
            fieldId: base.fieldId,
            fieldName: base.fieldName,
            mainItemId: base.mainItemId,
            language: base.language || descriptor.language,
            version: base.version || descriptor.version,
            position: 0,
            rangeStart: base.rangeStart,
            rangeEnd: base.rangeEnd,
            author: editContext?.user?.name,
            authorDisplayName: editContext?.user?.fullName,
            created: new Date().toISOString(),
            text,
            tags: tags.join(","),
            fieldValue: base.fieldValue,
        };
    };
    const handleReplySave = async (text, tags) => {
        if (!editContext?.currentItemDescriptor)
            return;
        // Always set the immediate comment as the parent being replied to.
        const newReply = buildReplyFrom(comment, text, tags);
        setIsSaving(true);
        try {
            const result = await createOrUpdateComment(newReply);
            if (result.type === "error" || result.type === "unauthorized") {
                console.error("Failed to save reply comment:", result);
                toast.error(result.details || result.summary || "Failed to save reply comment");
                return;
            }
            setIsReplying(false);
            await editContext.loadComments?.();
        }
        catch (error) {
            console.error("Failed to save reply comment:", error);
            toast.error(error instanceof Error ? error.message : "Failed to save reply comment");
        }
        finally {
            setIsSaving(false);
        }
    };
    const canReply = !comment.isNew && !comment.isResolved && !editContext?.readonly;
    if (isEditing) {
        return (_jsx("div", { ref: ref, className: "mb-3 rounded-lg bg-white p-3 shadow-sm", children: _jsx(CommentEditor, { initialText: comment.text, onSave: handleSave, onCancel: handleCancel, isSaving: isSaving, availableTags: availableTags, selectedTags: comment.tags ? comment.tags.split(",").filter((t) => t.trim()) : [], placeholder: "Add a comment...", submitLabel: comment.isNew ? "Comment" : "Save", showTagSelector: true }) }));
    }
    return (_jsxs("div", { ref: ref, "data-testid": "comment", className: `mb-3 cursor-pointer rounded-lg border-2 bg-white p-3 shadow-sm hover:bg-gray-50 ${isSelected ? "border-blue-500" : "border-transparent"}`, onClick: async () => {
            const currentPageId = editContext?.currentItemDescriptor?.id;
            if (currentPageId &&
                comment.mainItemId &&
                comment.mainItemId !== currentPageId) {
                await editContext?.loadItem({
                    id: comment.mainItemId,
                    language: comment.language,
                    version: comment.version,
                });
            }
            editContext?.setSelectedComment(comment);
            editContext?.setScrollIntoView(comment.itemId);
            if (!editContext?.isMobile) {
                editContext?.select([comment.itemId]);
                if (comment.fieldId) {
                    fieldsContext?.setFocusedField({
                        fieldId: comment.fieldId,
                        item: {
                            id: comment.itemId,
                            language: comment.language,
                            version: comment.version,
                        },
                    }, false);
                }
            }
        }, children: [_jsx(CommentView, { comment: comment, canEdit: canEdit, canDelete: canDelete, canResolve: canResolve, availableTags: availableTags, basePageName: editContext?.currentItemDescriptor?.name, basePageId: editContext?.currentItemDescriptor?.id, parentSnippet: parentSnippet, onEdit: () => setIsEditing(true), onDelete: handleDelete, onResolve: handleResolve, onUnresolve: handleUnresolve, onAiAction: canUseAi ? handleAiAction : undefined, onReply: canReply ? () => setIsReplying((x) => !x) : undefined }), isReplying && (_jsx("div", { className: "mt-3 border-t pt-3", children: _jsx(CommentEditor, { onSave: handleReplySave, onCancel: () => setIsReplying(false), isSaving: isSaving, availableTags: availableTags, placeholder: "Write your reply...", submitLabel: "Reply", compact: true }) }))] }, comment.id));
}
//# sourceMappingURL=Comment.js.map