"use client";
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useEffect, useState } from "react";
import uuid from "react-uuid";
import { AlertTriangle, Loader2, Rocket } from "lucide-react";
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 { Checkbox } from "../../components/ui/checkbox";
import { Label } from "../../components/ui/label";
import { LanguageSelectionGrid } from "../../components/ui/LanguageSelectionGrid";
import { StyledDialogTitle } from "../../components/ui/styled-dialog-title";
import { Select } from "../../components/ui/select";
import { LoadingState } from "./LoadingState";
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.",
    },
];
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 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 areAllTargetsSelected = targets.length > 0 &&
        targets.every((target) => selectedTargets.includes(target.targetDatabase));
    const areSomeTargetsSelected = targets.some((target) => selectedTargets.includes(target.targetDatabase));
    const toggleAllTargets = () => {
        setSelectedTargets(areAllTargetsSelected
            ? []
            : targets.map((target) => target.targetDatabase));
    };
    const areAllLanguagesSelected = languages.length > 0 &&
        languages.every((language) => selectedLanguages.includes(language.languageCode));
    const areSomeLanguagesSelected = languages.some((language) => selectedLanguages.includes(language.languageCode));
    const toggleAllLanguages = () => {
        setSelectedLanguages(areAllLanguagesSelected
            ? []
            : languages.map((language) => language.languageCode));
    };
    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 ? (_jsx(LoadingState, { message: "Loading publish options..." })) : (_jsxs("div", { className: "space-y-5", children: [!item.isFinalState && item.workflowState && (_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, { strokeWidth: 1, className: "mt-0.5 h-4 w-4 shrink-0" }), _jsxs("span", { children: ["This item is in the \"", item.workflowState, "\" workflow state. Move it to a final workflow state before publishing."] })] })), 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: "space-y-3", children: [_jsx(Label, { htmlFor: "publish-mode", className: "text-sm", 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("section", { className: "space-y-3", children: [_jsxs("div", { className: "flex items-center justify-between gap-3", children: [_jsxs("div", { children: [_jsx("div", { className: "text-sm font-medium", children: "Languages" }), _jsx("div", { className: "text-2xs text-muted-foreground", children: "Choose which languages to publish." })] }), languages.length > 1 && (_jsxs("label", { className: "text-neutral-grey-50 hover:text-neutral-grey-100 flex cursor-pointer items-center gap-1.5 text-[11px] font-medium transition-colors", children: [_jsx("input", { type: "checkbox", checked: areAllLanguagesSelected, ref: (input) => {
                                                            if (input) {
                                                                input.indeterminate =
                                                                    areSomeLanguagesSelected &&
                                                                        !areAllLanguagesSelected;
                                                            }
                                                        }, onChange: toggleAllLanguages, className: "border-border-default h-3 w-3 rounded text-[var(--color-highlight-100)] accent-[var(--color-highlight-100)] focus:ring-[var(--color-highlight-100)]", "data-testid": "select-all-languages-checkbox" }), "Select all"] }))] }), _jsx(LanguageSelectionGrid, { headerless: true, languages: languages.map((language) => ({
                                            code: language.languageCode,
                                            name: language.name,
                                            icon: language.icon,
                                        })), selectedLanguageCodes: selectedLanguages, onSelectedLanguageCodesChange: setSelectedLanguages, className: "max-w-none border-none", bodyClassName: "p-0", checkboxTestIdPrefix: "publish-language-checkbox", getLanguageTestId: (language) => `publish-language-${language.code}`, emptyState: "No languages available." })] }), _jsxs("section", { className: "space-y-3", children: [_jsx("div", { className: "text-sm font-medium", 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." })] })] })] })] }), _jsxs("section", { className: "space-y-3", children: [_jsxs("div", { className: "flex items-center justify-between gap-3", children: [_jsxs("div", { children: [_jsx("div", { className: "text-sm font-medium", children: "Publishing targets" }), _jsx("div", { className: "text-2xs text-muted-foreground", children: "Choose where the item should be published." })] }), targets.length > 1 && (_jsxs("label", { className: "text-neutral-grey-50 hover:text-neutral-grey-100 flex cursor-pointer items-center gap-1.5 text-[11px] font-medium transition-colors", children: [_jsx("input", { type: "checkbox", checked: areAllTargetsSelected, ref: (input) => {
                                                            if (input) {
                                                                input.indeterminate =
                                                                    areSomeTargetsSelected && !areAllTargetsSelected;
                                                            }
                                                        }, onChange: toggleAllTargets, className: "border-border-default h-3 w-3 rounded text-[var(--color-highlight-100)] accent-[var(--color-highlight-100)] focus:ring-[var(--color-highlight-100)]", "data-testid": "select-all-targets-checkbox" }), "Select all"] }))] }), _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: [_jsx("span", { className: "text-sm font-medium", children: target.name }), _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));
                                        }) })] }), (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, { strokeWidth: 1, className: "mt-0.5 h-4 w-4 shrink-0" }), _jsx("span", { children: "Select at least one target and one language before publishing." })] }))] })) }), _jsxs(DialogFooter, { className: "mt-auto shrink-0 border-t bg-white px-6 py-4", children: [_jsx(Button, { variant: "outline", onClick: () => onClose(null), children: "Cancel" }), _jsx(Button, { onClick: submit, disabled: !canSubmit, "data-testid": "publish-submit", children: isSubmitting ? (_jsxs(_Fragment, { children: [_jsx(Loader2, { strokeWidth: 1, className: "mr-2 h-4 w-4 animate-spin" }), "Starting..."] })) : ("Publish") })] })] }) }));
}
//# sourceMappingURL=PublishItemDialog.js.map