import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useEffect, useState } from "react";
import { useUserSession } from "@vertesia/ui/session";
import { Button, Spinner, useToast } from "@vertesia/ui/core";
import { JSONDisplay, MarkdownRenderer } from "@vertesia/ui/widgets";
import { ImageRenditionFormat } from "@vertesia/common";
import { Copy, Download, SquarePen } from "lucide-react";
import { PropertiesEditorModal } from "./PropertiesEditorModal";
import { NavLink } from "@vertesia/ui/router";
export function ContentOverview({ object, loadText, refetch, }) {
    const { client, store } = useUserSession();
    const [isLoadingText, setIsLoadingText] = useState(false);
    const [text, setText] = useState(object.text);
    const [imageUrl, setImageUrl] = useState();
    const [isPropertiesModalOpen, setPropertiesModalOpen] = useState(false);
    const toast = useToast();
    const [viewCode, setViewCode] = useState(false);
    const VIEW_JSON = "JSON";
    const VIEW_TEXT = "Preview";
    const handleOpenPropertiesModal = () => {
        setPropertiesModalOpen(true);
    };
    const handleClosePropertiesModal = () => {
        setPropertiesModalOpen(false);
    };
    useEffect(() => {
        if (loadText && !text) {
            setIsLoadingText(true);
            store.objects
                .getObjectText(object.id)
                .then((res) => {
                setText(res.text);
            })
                .catch((err) => {
                console.error("Failed to load text", err);
            })
                .finally(() => {
                setIsLoadingText(false);
            });
        }
    }, [loadText]);
    const handleCopyContent = async (content, type) => {
        try {
            await navigator.clipboard.writeText(content);
            toast({
                status: "success",
                title: `${type === "text" ? "Content" : "Properties"} copied`,
                description: `Successfully copied ${type} to clipboard`,
                duration: 2000,
            });
        }
        catch (err) {
            console.error(`Failed to copy ${type}:`, err);
            toast({
                status: "error",
                title: "Copy failed",
                description: `Failed to copy ${type} to clipboard`,
                duration: 5000,
            });
        }
    };
    const handleExportDocument = async (format) => {
        try {
            // Request document rendition from the server
            const response = await client.objects.getRendition(object.id, {
                format: format, // We're extending the format type
                generate_if_missing: true,
                sign_url: true,
            });
            if (response.status === "generating") {
                toast({
                    status: "info",
                    title: "Generating document",
                    description: `Please wait while we prepare your ${format.toUpperCase()} file...`,
                    duration: 5000,
                });
                // Poll for completion
                setTimeout(() => handleExportDocument(format), 3000);
                return;
            }
            if (response.status === "failed") {
                throw new Error("Document generation failed");
            }
            // Download the generated file or open in new window
            if (response.renditions && response.renditions.length > 0) {
                const downloadUrl = response.renditions[0];
                if (format === 'pdf') {
                    // Open PDF in new window
                    window.open(downloadUrl, '_blank');
                    toast({
                        status: "success",
                        title: "PDF opened",
                        description: "PDF document opened in a new window",
                        duration: 2000,
                    });
                }
                else {
                    // Download DOCX file
                    const link = document.createElement("a");
                    link.href = downloadUrl;
                    link.download = `${object.name || "document"}.${format}`;
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                    toast({
                        status: "success",
                        title: "Document exported",
                        description: `Successfully exported to ${format.toUpperCase()} format`,
                        duration: 2000,
                    });
                }
            }
        }
        catch (err) {
            console.error(`Failed to export document as ${format}:`, err);
            toast({
                status: "error",
                title: "Export failed",
                description: `Failed to export document to ${format.toUpperCase()} format`,
                duration: 5000,
            });
        }
    };
    const handleExportDocx = () => handleExportDocument("docx");
    const handleExportPdf = () => handleExportDocument("pdf");
    const content = object.content;
    const isImage = content &&
        content.source &&
        content.type &&
        content.type.startsWith("image/");
    const isMarkdownOrText = content &&
        content.type &&
        (content.type === "text/markdown" || content.type === "text/plain");
    // Check for markdown indicators, ignoring any HTML comments
    const seemsMarkdown = text &&
        // Look for markdown indicators
        (text.includes("\n#") ||
            text.includes("\n*") ||
            text.includes("\n+") ||
            text.includes("!["));
    useEffect(() => {
        if (isImage) {
            client.objects
                .getRendition(object.id, {
                format: ImageRenditionFormat.jpeg,
                generate_if_missing: false,
                sign_url: true,
            })
                .then((r) => {
                if (r.status === "found") {
                    return r.renditions?.length ? r.renditions[0] : null;
                }
                else {
                    return object;
                }
            })
                .catch(() => {
                return object;
            })
                .then(() => {
                client.files
                    .getDownloadUrl(object.content.source)
                    .then((r) => {
                    setImageUrl(r.url);
                });
            });
        }
    }, []);
    return (_jsxs("div", { className: "w-full", children: [_jsxs("div", { className: "flex flex-col lg:flex-row lg:gap-8", children: [_jsxs("div", { className: "w-full lg:w-1/2", children: [_jsxs("div", { className: "h-[41px] text-lg font-semibold mb-4 border-b flex justify-between items-center", children: [_jsxs("div", { className: "flex items-center gap-1", children: ["Properties", _jsx(Button, { variant: "outline", size: "sm", alt: `${viewCode ? "Preview" : "View in JSON format"}`, onClick: () => setViewCode(!viewCode), children: viewCode ? VIEW_TEXT : VIEW_JSON })] }), _jsxs("div", { className: "flex items-center gap-2", children: [object.properties && (_jsx(Button, { variant: "ghost", size: "sm", title: "Copy properties", onClick: () => handleCopyContent(JSON.stringify(object.properties, null, 2), "properties"), children: _jsx(Copy, { className: "size-4" }) })), _jsx(Button, { variant: "ghost", size: "sm", onClick: handleOpenPropertiesModal, title: "Edit properties", className: "flex items-center gap-2", children: _jsx(SquarePen, { className: "size-4" }) })] })] }), object.properties ? (_jsx(JSONDisplay, { value: object.properties, viewCode: viewCode })) : (_jsx("div", { children: "No properties defined" })), isImage && (_jsxs("div", { className: "my-4", children: [_jsx("div", { className: "h-[41px] text-lg font-semibold mb-4 border-b flex justify-between items-center", children: _jsx("span", { className: "py-1", children: "Image" }) }), imageUrl ? (_jsx("img", { src: imageUrl, alt: object.name, className: "w-full object-contain" })) : (_jsx(Spinner, { size: "md" }))] }))] }), _jsxs("div", { className: "w-full lg:w-1/2 mt-4 lg:mt-0", children: [_jsxs("div", { className: "h-[41px] text-lg font-semibold mb-4 border-b flex justify-between items-center", children: [_jsx("span", { className: "py-1", children: "Text" }), _jsxs("div", { className: "flex items-center gap-2", children: [text && (_jsx(Button, { variant: "ghost", size: "sm", title: "Copy text", onClick: () => handleCopyContent(text, "text"), className: "flex items-center gap-2", children: _jsx(Copy, { className: "h-4 w-4" }) })), (isMarkdownOrText || seemsMarkdown) && text && (_jsxs(_Fragment, { children: [_jsxs(Button, { variant: "ghost", size: "sm", onClick: handleExportDocx, className: "flex items-center gap-2", children: [_jsx(Download, { className: "h-4 w-4" }), "DOCX"] }), _jsxs(Button, { variant: "ghost", size: "sm", onClick: handleExportPdf, className: "flex items-center gap-2", children: [_jsx(Download, { className: "h-4 w-4" }), "PDF"] })] }))] })] }), isLoadingText && _jsx(Spinner, { size: "md" }), text ? (_jsx("div", { className: "border shadow-xs rounded-xs max-w-7xl", children: seemsMarkdown ? (_jsx("div", { className: "vprose prose-sm p-1", children: _jsx(MarkdownRenderer, { components: {
                                            a: ({ node, ...props }) => {
                                                const href = props.href || "";
                                                if (href.includes("/store/objects/")) {
                                                    return (_jsx(NavLink, { topLevelNav: true, href: href, className: "text-info", children: props.children }));
                                                }
                                                return _jsx("a", { ...props, "data-debug": "test", target: "_blank", rel: "noopener noreferrer" });
                                            },
                                            p: ({ node, ...props }) => (_jsx("p", { ...props, className: `my-0` })),
                                            pre: ({ node, ...props }) => (_jsx("pre", { ...props, className: `my-2 p-2 rounded` })),
                                            code: ({ node, className, children, ...props }) => {
                                                const match = /language-(\w+)/.exec(className || "");
                                                const isInline = !match;
                                                return (_jsx("code", { ...props, className: isInline
                                                        ? `px-1.5 py-0.5 rounded`
                                                        : "text-muted", children: children }));
                                            },
                                            h1: ({ node, ...props }) => (_jsx("h1", { ...props, className: `font-bold text-2xl my-2` })),
                                            h2: ({ node, ...props }) => (_jsx("h2", { ...props, className: `font-bold text-xl my-2` })),
                                            h3: ({ node, ...props }) => (_jsx("h3", { ...props, className: `font-bold text-lg my-2` })),
                                            li: ({ node, ...props }) => (_jsx("li", { ...props })),
                                        }, children: text }) })) : (_jsx("pre", { className: "text-wrap bg-muted text-muted p-2", children: text })) })) : (_jsx("div", { children: "No content" }))] })] }), _jsx(PropertiesEditorModal, { isOpen: isPropertiesModalOpen, onClose: handleClosePropertiesModal, object: object, refetch: refetch })] }));
}
//# sourceMappingURL=ContentOverview.js.map