"use client";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import * as React from "react";
import { useEffect, useState } from "react";
import uuid from "react-uuid";
import { MessageCirclePlus } from "lucide-react";
import { useEditContext, useFieldsEditContext, } from "../client/editContext";
import { createOrUpdateComment } from "../services/reviewsService";
import { toast } from "sonner";
import { Popover, PopoverContent, PopoverTrigger, PopoverAnchor, } from "../../components/ui/popover";
import { CommentEditor } from "./CommentEditor";
import * as ReactDOM from "react-dom/client";
export function CommentPopover({ children, editContext: externalEditContext, position, onClose, initialField, initialRange, }) {
    const [isOpen, setIsOpen] = useState(!!position);
    const [saving, setSaving] = useState(false);
    const contextFromHook = useEditContext();
    const editContext = externalEditContext || contextFromHook;
    const availableTags = editContext?.availableCommentTags || [];
    const fieldsContext = useFieldsEditContext();
    const contentRef = React.useRef(null);
    useEffect(() => {
        if (position)
            setIsOpen(true);
    }, [position?.x, position?.y]);
    // Tags are now provided by editContext.availableCommentTags
    const handleSave = async (text, tags) => {
        if (!editContext || !text || saving)
            return;
        const descriptor = editContext.item?.descriptor;
        if (!descriptor)
            return;
        const snapshotField = initialField || fieldsContext?.focusedField;
        const snapshotRange = initialRange || editContext.selectedRange;
        const itemId = snapshotField?.item.id ||
            (editContext.selection.length > 0
                ? editContext.selection[0]
                : undefined) ||
            descriptor.id;
        if (!itemId)
            return;
        const language = descriptor.language;
        const version = descriptor.version;
        const getFieldName = async () => {
            if (!snapshotField)
                return undefined;
            const field = await editContext.itemsRepository.getField(snapshotField);
            return field?.name;
        };
        const getItemName = async () => {
            const item = await editContext.itemsRepository.getItem({
                id: itemId,
                language,
                version,
            });
            return item?.name;
        };
        setSaving(true);
        try {
            const newComment = {
                id: uuid(),
                isNew: false,
                itemId,
                itemName: await getItemName(),
                fieldId: snapshotField?.fieldId,
                fieldName: await getFieldName(),
                mainItemId: descriptor.id,
                language,
                version,
                position: 0,
                rangeStart: snapshotRange?.startOffset || 0,
                rangeEnd: snapshotRange?.endOffset || 0,
                author: editContext.user?.name,
                authorDisplayName: editContext.user?.fullName,
                date: new Date().toISOString(),
                text: text,
                tags: tags.join(","),
            };
            editContext.setComments([newComment, ...editContext.comments]);
            editContext.setSelectedComment(newComment);
            try {
                const item = await editContext.itemsRepository.getItem({
                    id: itemId,
                    language,
                    version,
                });
                if (item && newComment.fieldId) {
                    newComment.fieldValue = item.fields.find((f) => f.id === newComment.fieldId)?.rawValue;
                }
            }
            catch { }
            const result = await createOrUpdateComment(newComment);
            if (result.type === "error" || result.type === "unauthorized") {
                console.error("Failed to save comment:", result);
                toast.error(result.details || result.summary || "Failed to save comment");
                return;
            }
            editContext.loadComments();
        }
        finally {
            setSaving(false);
            setIsOpen(false);
            onClose?.();
        }
    };
    const handleCancel = () => {
        setIsOpen(false);
        onClose?.();
    };
    return (_jsxs(Popover, { open: isOpen, onOpenChange: (open) => {
            setIsOpen(open);
            if (!open)
                onClose?.();
        }, enableIframeClickDetection: false, modal: true, children: [position && (_jsx("div", { style: {
                    position: "fixed",
                    left: position.x,
                    top: position.y,
                    width: 1,
                    height: 1,
                    pointerEvents: "none",
                }, children: _jsx(PopoverAnchor, {}) })), !position && (_jsx(PopoverTrigger, { asChild: true, children: (children ?? _jsx(MessageCirclePlus, { size: 16, strokeWidth: 1 })) })), _jsx(PopoverContent, { ref: contentRef, tabIndex: -1, className: "w-96 p-4", "data-testid": "add-comment-popover", side: "bottom", align: "start", onOpenAutoFocus: (e) => {
                    e.preventDefault();
                    contentRef.current?.focus();
                }, onInteractOutside: (e) => {
                    const target = e.target;
                    if (target && target.closest('[data-slot="tooltip-content"]')) {
                        e.preventDefault();
                    }
                }, onPointerDownOutside: (e) => {
                    const target = e.target;
                    if (target && target.closest('[data-slot="tooltip-content"]')) {
                        e.preventDefault();
                    }
                }, onFocusOutside: (e) => {
                    const target = e.target;
                    if (target && target.closest('[data-slot="tooltip-content"]')) {
                        e.preventDefault();
                    }
                }, onMouseDown: (e) => e.stopPropagation(), onClick: (e) => e.stopPropagation(), children: _jsxs("div", { className: "space-y-3", children: [_jsx("div", { className: "font-medium", children: "Add Comment" }), _jsx(CommentEditor, { onSave: handleSave, onCancel: handleCancel, isSaving: saving, availableTags: availableTags, placeholder: "Write your comment...", submitLabel: "Add Comment", autoFocus: true })] }) })] }));
}
export function showCommentPopoverAt(position, editContext, options) {
    const container = document.createElement("div");
    document.body.appendChild(container);
    const root = ReactDOM.createRoot(container);
    const handleClose = () => {
        root.unmount();
        if (container.parentNode)
            container.parentNode.removeChild(container);
    };
    root.render(_jsx(CommentPopover, { editContext: editContext, position: position, onClose: handleClose, initialField: options?.field, initialRange: options?.range }));
}
//# sourceMappingURL=CommentPopover.js.map