"use client";
import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useState } from "react";
import uuid from "react-uuid";
import { Rocket } from "lucide-react";
import { toast } from "sonner";
import { useEditContext } from "../client/editContext";
import { getLanguagesAndVersions } from "../services/contentService";
import { Dialog, DialogContent, DialogFooter, } from "../../components/ui/dialog";
import { Button } from "../../components/ui/button";
import { StyledDialogTitle } from "../../components/ui/styled-dialog-title";
import { Spinner } from "./Spinner";
import { WorkboxItemsTable } from "./WorkboxItemsTable";
/**
 * Lists the current page's workbox items in a modal and publishes the current
 * item directly (smart publish to all available targets, current language).
 * Per-row workflow commands act inline; the list refreshes in place as
 * workboxItems updates.
 */
export function PublishDialog({ onClose }) {
    const editContext = useEditContext();
    const [isPublishing, setIsPublishing] = useState(false);
    if (!editContext)
        return null;
    const currentPublishDescriptor = editContext.currentItemDescriptor;
    const currentPublishItem = editContext.item;
    const currentPublishWorkboxItem = editContext.workboxItems.find((item) => item.item.id === currentPublishDescriptor?.id &&
        item.item.language === currentPublishDescriptor?.language &&
        item.item.version === currentPublishDescriptor?.version);
    // The current item is blocked from publishing only when it sits in a
    // non-final workflow state. Items with no workflow report isPublishable
    // = false from the server (the flag is only set for workflow items), so we
    // gate on an actual workflow state instead of the conflated flag.
    const blockedByWorkflowState = !!currentPublishWorkboxItem?.workflowState &&
        !currentPublishWorkboxItem.isPublishable;
    const canPublishCurrentItem = !!currentPublishDescriptor &&
        !isPublishing &&
        !editContext.readonly &&
        !blockedByWorkflowState;
    const publishButtonTooltip = !currentPublishDescriptor
        ? "No current item is available to publish."
        : blockedByWorkflowState
            ? `Move this item to a final workflow state before publishing${currentPublishWorkboxItem?.workflowState
                ? ` (currently "${currentPublishWorkboxItem.workflowState}")`
                : ""}.`
            : "Publish the current item.";
    const publishCurrentItem = async () => {
        if (!currentPublishDescriptor || !canPublishCurrentItem)
            return;
        setIsPublishing(true);
        try {
            const item = currentPublishItem ||
                (await editContext.itemsRepository.getItem(currentPublishDescriptor));
            if (!item) {
                toast.error("Failed to load item for publishing.");
                return;
            }
            const result = await getLanguagesAndVersions(item.descriptor, {
                includePublishingTargets: true,
            });
            if (result.type !== "success" || !result.data) {
                toast.error(result.summary || result.details || "Failed to load publish options.");
                return;
            }
            const targetDatabases = (result.data.publishingTargets || []).map((target) => target.targetDatabase);
            if (targetDatabases.length === 0) {
                toast.error("No publishing targets are available for this item.");
                return;
            }
            const operation = {
                type: "publish-item",
                id: uuid(),
                date: new Date().toISOString(),
                title: `Publish ${item.displayName || item.name}`,
                description: `smart publish to ${targetDatabases.length} target(s)`,
                mainItem: item.descriptor,
                item: item.descriptor,
                targetDatabases,
                languages: [item.language],
                publishMode: "smart",
                includeSubitems: false,
                publishRelatedItems: false,
                canUndo: false,
            };
            const opResult = await editContext.operations.publishItem(operation);
            toast.success(`Publishing ${item.displayName || item.name}…`);
            onClose(opResult);
        }
        catch {
            toast.error("Failed to start publish.");
        }
        finally {
            setIsPublishing(false);
        }
    };
    return (_jsx(Dialog, { open: true, onOpenChange: (open) => {
            if (!open)
                onClose(null);
        }, children: _jsxs(DialogContent, { className: "flex max-w-4xl flex-col overflow-hidden border-none p-0 shadow-2xl", style: { maxHeight: "90vh" }, showCloseButton: true, "data-testid": "publish-dialog", children: [_jsx(StyledDialogTitle, { icon: _jsx(Rocket, { strokeWidth: 1 }), title: "Publish", subtitle: editContext.item?.displayName || editContext.item?.name }), _jsx("div", { className: "flex min-h-0 flex-1 flex-col overflow-y-auto px-6 py-5", children: _jsx("div", { className: "min-h-[12rem]", children: _jsx(WorkboxItemsTable, { items: editContext.workboxItems, isLoading: editContext.isWorkboxLoading, emptyMessage: "No items to publish." }) }) }), _jsxs(DialogFooter, { className: "mt-auto shrink-0 border-t bg-white px-6 py-4", children: [_jsx(Button, { variant: "outline", onClick: () => onClose(null), children: "Close" }), _jsx(Button, { onClick: publishCurrentItem, disabled: !canPublishCurrentItem, title: publishButtonTooltip, "data-testid": "publish-dialog-submit", children: isPublishing ? (_jsxs(_Fragment, { children: [_jsx(Spinner, { size: "sm" }), " Publishing..."] })) : (_jsxs(_Fragment, { children: [_jsx(Rocket, { className: "h-3.5 w-3.5", strokeWidth: 1 }), "Publish"] })) })] })] }) }));
}
//# sourceMappingURL=PublishDialog.js.map