"use client";
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useEffect, useMemo, useState } from "react";
import uuid from "react-uuid";
import { AlertTriangle, Globe, Loader2, Rocket, Send } from "lucide-react";
import { useEditContext } from "../client/editContext";
import { getLanguagesAndVersions } from "../services/contentService";
import { Dialog, DialogContent } from "../../components/ui/dialog";
import { Button } from "../../components/ui/button";
import { Checkbox } from "../../components/ui/checkbox";
import { Badge } from "../../components/ui/badge";
import { Label } from "../../components/ui/label";
import { StyledDialogTitle } from "../../components/ui/styled-dialog-title";
import { Select } from "../../components/ui/select";
import DialogButtons from "./DialogButtons";
const publishModeOptions = [
    {
        value: "smart",
        label: "Smart publish",
        description: "Publish only changes that are not already up to date.",
    },
    {
        value: "republish",
        label: "Republish",
        description: "Republish the selected content regardless of current state.",
    },
];
function statusVariant(status) {
    switch (status) {
        case "published":
            return "default";
        case "restricted":
        case "stale-published":
            return "destructive";
        case "not-published":
        case "version-mismatch":
        case "revision-mismatch":
            return "secondary";
        default:
            return "outline";
    }
}
function statusLabel(status) {
    switch (status) {
        case "published":
            return "Published";
        case "not-published":
            return "Not published";
        case "version-mismatch":
            return "Version mismatch";
        case "revision-mismatch":
            return "Out of date";
        case "restricted":
            return "Restricted";
        case "stale-published":
            return "Stale publish";
        case "not-valid-version":
            return "Not valid version";
        default:
            return status;
    }
}
export function PublishItemDialog({ item, onClose }) {
    const editContext = useEditContext();
    const [isLoading, setIsLoading] = useState(true);
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [targets, setTargets] = useState([]);
    const [languages, setLanguages] = useState([]);
    const [selectedTargets, setSelectedTargets] = useState([]);
    const [selectedLanguages, setSelectedLanguages] = useState([
        item.language,
    ]);
    const [publishMode, setPublishMode] = useState("smart");
    const [includeSubitems, setIncludeSubitems] = useState(false);
    const [publishRelatedItems, setPublishRelatedItems] = useState(false);
    const [loadError, setLoadError] = useState(null);
    useEffect(() => {
        let cancelled = false;
        async function loadData() {
            setIsLoading(true);
            setLoadError(null);
            const result = await getLanguagesAndVersions(item.descriptor, {
                includePublishingTargets: true,
            });
            if (cancelled)
                return;
            if (result.type !== "success" || !result.data) {
                setLoadError(result.summary || result.details || "Failed to load publish options.");
                setTargets([]);
                setSelectedTargets([]);
                setIsLoading(false);
                return;
            }
            const nextTargets = result.data.publishingTargets || [];
            const nextLanguages = result.data.languages || [];
            setTargets(nextTargets);
            setLanguages(nextLanguages);
            setSelectedTargets(nextTargets.map((target) => target.targetDatabase));
            const availableLanguages = nextLanguages.map((language) => language.languageCode);
            setSelectedLanguages(availableLanguages.includes(item.language)
                ? [item.language]
                : availableLanguages.slice(0, 1));
            setIsLoading(false);
        }
        loadData();
        return () => {
            cancelled = true;
        };
    }, [item.descriptor, item.language]);
    const publishSummary = useMemo(() => {
        if (targets.length === 0) {
            return {
                variant: "secondary",
                text: "No publishing targets found",
            };
        }
        if (targets.every((target) => target.status === "published")) {
            return {
                variant: "default",
                text: "Current version is already published to all targets",
            };
        }
        if (targets.some((target) => target.status === "restricted" || target.status === "stale-published")) {
            return {
                variant: "destructive",
                text: "Some targets have publish restrictions or stale published content",
            };
        }
        return {
            variant: "secondary",
            text: "Publishing will update one or more targets",
        };
    }, [targets]);
    const canSubmit = !!editContext &&
        !isLoading &&
        !isSubmitting &&
        !loadError &&
        selectedTargets.length > 0 &&
        selectedLanguages.length > 0 &&
        item.canWriteItem &&
        item.canWriteLanguage;
    const toggleTarget = (targetDatabase, checked) => {
        setSelectedTargets((prev) => checked
            ? Array.from(new Set([...prev, targetDatabase]))
            : prev.filter((value) => value !== targetDatabase));
    };
    const toggleLanguage = (language, checked) => {
        setSelectedLanguages((prev) => checked
            ? Array.from(new Set([...prev, language]))
            : prev.filter((value) => value !== language));
    };
    const submit = async () => {
        if (!editContext || !canSubmit)
            return;
        const operation = {
            type: "publish-item",
            id: uuid(),
            date: new Date().toISOString(),
            title: `Publish ${item.displayName || item.name}`,
            description: `${publishMode} publish to ${selectedTargets.length} target(s)`,
            mainItem: item.descriptor,
            item: item.descriptor,
            targetDatabases: selectedTargets,
            languages: selectedLanguages,
            publishMode,
            includeSubitems,
            publishRelatedItems,
            canUndo: false,
        };
        setIsSubmitting(true);
        try {
            const result = await editContext.operations.publishItem(operation);
            onClose(result);
        }
        catch {
            editContext.showToast?.("Failed to start publish.");
        }
        finally {
            setIsSubmitting(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, children: [_jsx(StyledDialogTitle, { icon: _jsx(Rocket, { strokeWidth: 1 }), title: "Publish Item", subtitle: item.displayName || item.name }), _jsx("div", { className: "flex min-h-0 flex-1 flex-col overflow-y-auto px-6 py-5", children: isLoading ? (_jsxs("div", { className: "flex flex-col items-center justify-center gap-3 py-16", children: [_jsx(Loader2, { className: "text-muted-foreground h-6 w-6 animate-spin" }), _jsx("span", { className: "text-muted-foreground text-sm", children: "Loading publish options..." })] })) : (_jsxs("div", { className: "space-y-5", children: [_jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [_jsx(Badge, { variant: publishSummary.variant, children: publishSummary.text }), !item.isFinalState && item.workflowState && (_jsxs(Badge, { variant: "outline", children: ["Workflow state: ", item.workflowState] }))] }), loadError && (_jsx("div", { className: "border-feedback-red bg-feedback-red-light text-feedback-red rounded-lg border px-4 py-3 text-sm", children: loadError })), !item.canWriteItem || !item.canWriteLanguage ? (_jsx("div", { className: "border-feedback-orange bg-feedback-orange-light text-feedback-orange rounded-lg border px-4 py-3 text-sm", children: "You do not have permission to publish this item in the current language." })) : null, _jsxs("section", { className: "grid gap-4 md:grid-cols-2", children: [_jsxs("div", { className: "space-y-2", children: [_jsx(Label, { htmlFor: "publish-mode", children: "Publish mode" }), _jsx(Select, { id: "publish-mode", "data-testid": "publish-mode-select", value: publishMode, onValueChange: (value) => setPublishMode(value || "smart"), options: publishModeOptions, placeholder: "Select publish mode" })] }), _jsxs("div", { className: "bg-neutral-grey-5/60 text-muted-foreground rounded-xl border px-4 py-3 text-sm", children: [_jsx("div", { className: "text-foreground font-medium", children: "Current item" }), _jsxs("div", { className: "mt-1", children: [item.path, " | ", item.language, " | v", item.version] })] })] }), _jsxs("section", { className: "space-y-3 rounded-xl border p-4", children: [_jsxs("div", { className: "flex items-center justify-between gap-3", children: [_jsxs("div", { children: [_jsx("div", { className: "text-sm font-semibold", children: "Publishing targets" }), _jsx("div", { className: "text-2xs text-muted-foreground", children: "Choose where the item should be published." })] }), _jsxs("div", { className: "flex gap-2", children: [_jsx(Button, { variant: "outline", size: "sm", type: "button", onClick: () => setSelectedTargets(targets.map((target) => target.targetDatabase)), children: "Select all" }), _jsx(Button, { variant: "outline", size: "sm", type: "button", onClick: () => setSelectedTargets([]), children: "Clear" })] })] }), _jsx("div", { className: "space-y-2", children: targets.map((target) => {
                                            const checked = selectedTargets.includes(target.targetDatabase);
                                            return (_jsxs("label", { className: "flex cursor-pointer items-start gap-3 rounded-lg border p-3", "data-testid": `publish-target-${target.targetDatabase}`, children: [_jsx(Checkbox, { checked: checked, onCheckedChange: (next) => toggleTarget(target.targetDatabase, !!next) }), _jsxs("div", { className: "min-w-0 flex-1", children: [_jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [_jsx("span", { className: "text-sm font-medium", children: target.name }), _jsx(Badge, { variant: statusVariant(target.status), children: statusLabel(target.status) })] }), _jsx("div", { className: "text-2xs text-muted-foreground mt-1", children: target.targetDatabase }), _jsx("div", { className: "text-muted-foreground mt-1 text-xs", children: target.message })] })] }, target.targetDatabase));
                                        }) })] }), _jsxs("section", { className: "space-y-3 rounded-xl border p-4", children: [_jsxs("div", { className: "flex items-center justify-between gap-3", children: [_jsxs("div", { children: [_jsxs("div", { className: "flex items-center gap-2 text-sm font-semibold", children: [_jsx(Globe, { className: "h-4 w-4" }), "Languages"] }), _jsx("div", { className: "text-muted-foreground text-xs", children: "Choose which languages to publish." })] }), _jsxs("div", { className: "flex gap-2", children: [_jsx(Button, { variant: "outline", size: "sm", type: "button", onClick: () => setSelectedLanguages(languages.map((language) => language.languageCode)), children: "Select all" }), _jsx(Button, { variant: "outline", size: "sm", type: "button", onClick: () => setSelectedLanguages([]), children: "Clear" })] })] }), _jsx("div", { className: "grid gap-2 md:grid-cols-2", children: languages.map((language) => {
                                            const checked = selectedLanguages.includes(language.languageCode);
                                            return (_jsxs("label", { className: "flex cursor-pointer items-center gap-3 rounded-lg border px-3 py-2", "data-testid": `publish-language-${language.languageCode}`, children: [_jsx(Checkbox, { checked: checked, onCheckedChange: (next) => toggleLanguage(language.languageCode, !!next) }), _jsxs("div", { className: "min-w-0 flex-1", children: [_jsx("div", { className: "text-sm font-medium", children: language.name }), _jsx("div", { className: "text-muted-foreground text-xs", children: language.languageCode })] }), _jsxs(Badge, { variant: "outline", children: [language.versions, " version", language.versions === 1 ? "" : "s"] })] }, language.languageCode));
                                        }) })] }), _jsxs("section", { className: "space-y-3 rounded-xl border p-4", children: [_jsx("div", { className: "text-sm font-semibold", children: "Options" }), _jsxs("div", { className: "space-y-3", children: [_jsxs("label", { className: "flex cursor-pointer items-start gap-3", children: [_jsx(Checkbox, { checked: includeSubitems, onCheckedChange: (checked) => setIncludeSubitems(!!checked), "data-testid": "publish-include-subitems" }), _jsxs("div", { children: [_jsx("div", { className: "text-sm font-medium", children: "Publish subitems" }), _jsx("div", { className: "text-2xs text-muted-foreground", children: "Include the selected item's descendants." })] })] }), _jsxs("label", { className: "flex cursor-pointer items-start gap-3", children: [_jsx(Checkbox, { checked: publishRelatedItems, onCheckedChange: (checked) => setPublishRelatedItems(!!checked), "data-testid": "publish-related-items" }), _jsxs("div", { children: [_jsx("div", { className: "text-sm font-medium", children: "Publish related items" }), _jsx("div", { className: "text-muted-foreground text-xs", children: "Include related content referenced by the item when Sitecore supports it." })] })] })] })] }), (selectedTargets.length === 0 ||
                                selectedLanguages.length === 0) && (_jsxs("div", { className: "border-feedback-orange bg-feedback-orange-light text-feedback-orange flex items-start gap-2 rounded-lg border px-4 py-3 text-sm", children: [_jsx(AlertTriangle, { className: "mt-0.5 h-4 w-4 shrink-0" }), _jsx("span", { children: "Select at least one target and one language before publishing." })] }))] })) }), _jsxs(DialogButtons, { children: [_jsx(Button, { variant: "outline", size: "sm", onClick: () => onClose(null), children: "Cancel" }), _jsx(Button, { size: "sm", onClick: submit, disabled: !canSubmit, "data-testid": "publish-submit", children: isSubmitting ? (_jsxs(_Fragment, { children: [_jsx(Loader2, { className: "mr-2 h-4 w-4 animate-spin" }), "Starting..."] })) : (_jsxs(_Fragment, { children: [_jsx(Send, { className: "mr-2 h-4 w-4" }), "Publish"] })) })] })] }) }));
}
//# sourceMappingURL=PublishItemDialog.js.map