import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useState, useEffect } from "react";
import { Dialog, DialogContent, DialogHeader, DialogTitle, } from "../../components/ui/dialog";
import { Button } from "../../components/ui/button";
import { Input } from "../../components/ui/input";
import { Label } from "../../components/ui/label";
import { Checkbox } from "../../components/ui/checkbox";
import { Loader2, AlertTriangle, Settings2 } from "lucide-react";
import { useEditContext } from "../client/editContext";
import { LanguageSelector } from "../../components/ui/LanguageSelector";
import { updateReviewSettings } from "../services/reviewsService";
import DialogButtons from "../ui/DialogButtons";
export function EditReviewSettingsDialog({ open, onOpenChange, review, items, reviewersCount, onUpdated, }) {
    const editContext = useEditContext();
    const [languageMode, setLanguageMode] = useState("single");
    const [selectedLanguages, setSelectedLanguages] = useState([]);
    const [language, setLanguage] = useState("en");
    const [secret, setSecret] = useState("");
    const [secretConfirm, setSecretConfirm] = useState("");
    const [showSecretFields, setShowSecretFields] = useState(false);
    const [showRemoveConfirm, setShowRemoveConfirm] = useState(false);
    const [updateWorkflowOnCompletion, setUpdateWorkflowOnCompletion] = useState(false);
    const [shareCommentsAndSuggestions, setShareCommentsAndSuggestions] = useState(false);
    const [requiredApprovals, setRequiredApprovals] = useState("1");
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(null);
    const [showErrors, setShowErrors] = useState(false);
    const [originalLanguages, setOriginalLanguages] = useState([]);
    const [originalLanguageMode, setOriginalLanguageMode] = useState("single");
    // Initialize form when dialog opens or review changes
    useEffect(() => {
        if (open && review) {
            // Determine current language mode from review.language
            let initialLanguages = [];
            let initialMode = "single";
            if (review.language === "*") {
                initialMode = "all";
                initialLanguages = ["*"];
                setLanguageMode("all");
                setSelectedLanguages(["*"]);
            }
            else if (review.language === "mixed") {
                initialMode = "multiple";
                setLanguageMode("multiple");
                // For mixed mode, extract languages from items
                if (items && items.length > 0) {
                    const languagesFromItems = Array.from(new Set(items.map((item) => item.language).filter((lang) => lang !== "*")));
                    initialLanguages = languagesFromItems;
                    setSelectedLanguages(languagesFromItems);
                }
                else {
                    // If no items available, default to empty
                    setSelectedLanguages([]);
                }
            }
            else {
                initialMode = "single";
                initialLanguages = [review.language];
                setLanguageMode("single");
                setLanguage(review.language);
                setSelectedLanguages([review.language]);
            }
            // Store original languages and mode for comparison
            setOriginalLanguages(initialLanguages);
            setOriginalLanguageMode(initialMode);
            // Reset secret fields
            setSecret("");
            setSecretConfirm("");
            setShowSecretFields(false);
            setShowRemoveConfirm(false);
            setUpdateWorkflowOnCompletion(review.updateWorkflowOnCompletion ?? false);
            setShareCommentsAndSuggestions(review.shareCommentsAndSuggestions ?? false);
            setRequiredApprovals((review.requiredApprovals ?? 1).toString());
            setError(null);
            setShowErrors(false);
        }
    }, [open, review, items]);
    // Calculate removed languages
    const getRemovedLanguages = () => {
        if (!review)
            return [];
        // Get current selected languages based on mode
        let currentLanguages;
        if (languageMode === "all") {
            currentLanguages = ["*"];
        }
        else if (languageMode === "multiple") {
            currentLanguages = selectedLanguages;
        }
        else {
            currentLanguages = [language];
        }
        // If original was "all", switching to specific languages removes all other languages
        if (originalLanguageMode === "all" && languageMode !== "all") {
            // When switching from "all" to specific languages, we're effectively removing all other languages
            // Return a special marker to indicate languages are being removed
            return ["*"]; // Special marker to indicate languages are being removed
        }
        // If switching from single/multiple to "all", no languages are removed
        if (languageMode === "all" && originalLanguageMode !== "all") {
            return [];
        }
        // Compare original languages with current languages
        const removed = originalLanguages.filter((lang) => !currentLanguages.includes(lang));
        return removed;
    };
    const removedLanguages = getRemovedLanguages();
    const hasRemovedLanguages = removedLanguages.length > 0;
    const handleSave = async () => {
        setShowErrors(true);
        setError(null);
        // Validate language selection based on mode
        if (languageMode === "single" && !language) {
            setError("Language is required");
            return;
        }
        if (languageMode === "multiple" && selectedLanguages.length === 0) {
            setError("Please select at least one language");
            return;
        }
        if (showSecretFields && secret !== secretConfirm) {
            setError("Secrets do not match");
            return;
        }
        // Validate RequiredApprovals
        const requiredApprovalsNum = requiredApprovals
            ? parseInt(requiredApprovals, 10)
            : 1;
        if (isNaN(requiredApprovalsNum) || requiredApprovalsNum < 1) {
            setError("Required Approvals must be at least 1");
            return;
        }
        if (reviewersCount && requiredApprovalsNum > reviewersCount) {
            setError(`Required Approvals (${requiredApprovalsNum}) cannot exceed the number of reviewers (${reviewersCount})`);
            return;
        }
        if (!review) {
            setError("Review not found");
            return;
        }
        setLoading(true);
        try {
            // Build languages array based on mode
            let languages;
            if (languageMode === "all") {
                languages = ["*"];
            }
            else if (languageMode === "multiple") {
                languages = selectedLanguages;
            }
            else {
                languages = [language];
            }
            // Determine secret handling:
            // - If showSecretFields is true and secret has value: set/change secret
            // - If showRemoveConfirm is true: remove secret (use removeSecret flag)
            // - Otherwise: don't change secret (undefined)
            const secretToSend = showSecretFields && secret ? secret : undefined;
            const removeSecret = showRemoveConfirm ? true : undefined;
            await updateReviewSettings(review.reviewId, languages, secretToSend, updateWorkflowOnCompletion, requiredApprovalsNum, removeSecret, shareCommentsAndSuggestions);
            // Success - refresh and close
            onUpdated();
            onOpenChange(false);
        }
        catch (err) {
            setError(err instanceof Error ? err.message : "Failed to update review settings");
        }
        finally {
            setLoading(false);
        }
    };
    return (_jsx(Dialog, { open: open, onOpenChange: onOpenChange, children: _jsxs(DialogContent, { className: "flex max-w-2xl overflow-hidden border-none p-0 shadow-2xl", children: [_jsx(DialogHeader, { className: "bg-neutral-grey-5/50 border-b px-6 py-4", children: _jsxs(DialogTitle, { className: "flex items-center gap-2 text-xl font-semibold tracking-tight", children: [_jsx("div", { className: "bg-primary/10 text-primary flex h-8 w-8 items-center justify-center rounded-lg", children: _jsx(Settings2, { className: "h-5 w-5" }) }), "Edit Review Settings"] }) }), _jsxs("div", { className: "flex min-h-0 flex-1 flex-col overflow-hidden", children: [_jsx("div", { className: "flex min-h-0 flex-1 flex-col overflow-y-auto px-6 pb-4", children: _jsxs("div", { className: "flex flex-col gap-6 pt-6", children: [_jsxs("div", { className: "flex flex-col gap-3", children: [_jsx("label", { className: "text-neutral-grey-100 text-sm font-semibold", children: "Language" }), _jsxs("div", { className: "flex flex-col gap-4", children: [_jsxs("div", { className: "flex items-center gap-6", children: [_jsxs("label", { className: "flex cursor-pointer items-center gap-2", children: [_jsx("input", { type: "radio", name: "languageMode", checked: languageMode === "single", onChange: () => {
                                                                            setLanguageMode("single");
                                                                            setLanguage(selectedLanguages[0] || language);
                                                                        }, className: "accent-primary h-4 w-4 cursor-pointer" }), _jsx("span", { className: "text-neutral-grey-100 text-xs", children: "Single Language" })] }), _jsxs("label", { className: "flex cursor-pointer items-center gap-2", children: [_jsx("input", { type: "radio", name: "languageMode", checked: languageMode === "multiple", onChange: () => setLanguageMode("multiple"), className: "accent-primary h-4 w-4 cursor-pointer" }), _jsx("span", { className: "text-neutral-grey-100 text-xs", children: "Multiple Languages" })] }), _jsxs("label", { className: "flex cursor-pointer items-center gap-2", children: [_jsx("input", { type: "radio", name: "languageMode", checked: languageMode === "all", onChange: () => setLanguageMode("all"), className: "accent-primary h-4 w-4 cursor-pointer" }), _jsx("span", { className: "text-neutral-grey-100 text-xs", children: "All Languages" })] })] }), languageMode === "single" && (_jsx("div", { className: "max-w-xs", children: _jsx(LanguageSelector, { selectedLanguage: language, onLanguageSelected: (lang) => {
                                                                setLanguage(lang.languageCode);
                                                                setSelectedLanguages([lang.languageCode]);
                                                            }, showAllLanguages: true }) })), languageMode === "multiple" && (_jsxs("div", { className: "border-border-default flex flex-col gap-2 rounded-lg border bg-white p-4 shadow-sm", children: [_jsxs("div", { className: "mb-2 flex items-center justify-between", children: [_jsx("span", { className: "text-neutral-grey-50 text-xs font-semibold tracking-wider", children: "Select Languages" }), _jsxs("div", { className: "flex gap-2", children: [_jsx(Button, { type: "button", variant: "ghost", size: "sm", onClick: () => {
                                                                                    const allLangs = editContext?.itemLanguages || [];
                                                                                    setSelectedLanguages(allLangs.map((l) => l.languageCode));
                                                                                }, className: "text-primary hover:bg-primary/5 h-7 px-2 text-xs", children: "Select All" }), _jsx(Button, { type: "button", variant: "ghost", size: "sm", onClick: () => setSelectedLanguages([]), className: "text-neutral-grey-50 hover:bg-neutral-grey-5 h-7 px-2 text-xs", children: "Clear" })] })] }), _jsx("div", { className: "grid max-h-48 grid-cols-2 gap-2 overflow-y-auto pr-2", children: (editContext?.itemLanguages || []).map((lang) => (_jsxs("label", { className: "hover:bg-neutral-grey-5 flex cursor-pointer items-center gap-2 rounded-md p-2 transition-colors", children: [_jsx(Checkbox, { checked: selectedLanguages.includes(lang.languageCode), onCheckedChange: (checked) => {
                                                                                if (checked) {
                                                                                    setSelectedLanguages([
                                                                                        ...selectedLanguages,
                                                                                        lang.languageCode,
                                                                                    ]);
                                                                                }
                                                                                else {
                                                                                    setSelectedLanguages(selectedLanguages.filter((l) => l !== lang.languageCode));
                                                                                }
                                                                            } }), _jsx("img", { src: lang.icon, className: "h-4 w-4", alt: lang.name }), _jsx("span", { className: "text-neutral-grey-100 text-xs font-medium", children: lang.name })] }, lang.languageCode))) }), showErrors && selectedLanguages.length === 0 && (_jsx("p", { className: "text-destructive mt-1 text-xs font-medium", children: "Please select at least one language" }))] })), languageMode === "all" && (_jsx("div", { className: "text-feedback-blue bg-feedback-blue-light border-feedback-blue rounded-lg border p-4 text-sm", children: "All available languages will be included in this review." })), hasRemovedLanguages && (_jsxs("div", { className: "bg-feedback-orange-light border-feedback-orange flex items-start gap-3 rounded-lg border p-4 shadow-sm", children: [_jsx(AlertTriangle, { className: "text-feedback-orange mt-0.5 h-5 w-5 shrink-0" }), _jsxs("div", { className: "flex-1", children: [_jsx("p", { className: "text-feedback-orange mb-1 text-sm leading-none font-semibold", children: "Removing languages will delete review decisions" }), _jsx("p", { className: "text-feedback-orange text-xs leading-relaxed", children: originalLanguageMode === "all"
                                                                            ? "Switching from 'All Languages' to specific languages will permanently delete all review decisions for languages not included in your selection."
                                                                            : (() => {
                                                                                const removedLangs = removedLanguages.filter((l) => l !== "*");
                                                                                if (removedLangs.length > 0) {
                                                                                    const langNames = removedLangs
                                                                                        .map((l) => {
                                                                                        const langObj = editContext?.itemLanguages?.find((lang) => lang.languageCode === l);
                                                                                        return langObj
                                                                                            ? langObj.name
                                                                                            : l.toUpperCase();
                                                                                    })
                                                                                        .join(", ");
                                                                                    return `Removing ${removedLangs.length > 1 ? "languages" : "language"} (${langNames}) will permanently delete all review decisions for ${removedLangs.length > 1 ? "those languages" : "that language"}.`;
                                                                                }
                                                                                return "Removing languages will permanently delete all review decisions for those languages.";
                                                                            })() })] })] }))] })] }), _jsxs("div", { className: "flex flex-col gap-3", children: [_jsx("label", { className: "text-neutral-grey-100 text-sm font-semibold", children: "Secret Protection" }), review?.requiresSecret ? (
                                            // Secret exists - show status and action buttons
                                            _jsxs("div", { className: "flex flex-col gap-3", children: [_jsxs("div", { className: "bg-feedback-green-light border-feedback-green flex items-center gap-2 rounded-lg border p-3", children: [_jsx("div", { className: "bg-feedback-green h-2 w-2 rounded-full" }), _jsx("span", { className: "text-feedback-green text-sm font-medium", children: "Secret protection is enabled" })] }), !showSecretFields && !showRemoveConfirm && (_jsxs("div", { className: "flex gap-2", children: [_jsx(Button, { type: "button", variant: "outline", size: "sm", onClick: () => {
                                                                    setShowSecretFields(true);
                                                                    setShowRemoveConfirm(false);
                                                                    setSecret("");
                                                                    setSecretConfirm("");
                                                                }, className: "flex-1", children: "Change Secret" }), _jsx(Button, { type: "button", variant: "outline", size: "sm", onClick: () => {
                                                                    setShowRemoveConfirm(true);
                                                                    setShowSecretFields(false);
                                                                    setSecret("");
                                                                    setSecretConfirm("");
                                                                }, className: "text-destructive hover:text-destructive hover:bg-destructive/10 flex-1", children: "Remove Secret" })] })), showRemoveConfirm && (_jsx("div", { className: "bg-feedback-orange-light border-feedback-orange flex flex-col gap-3 rounded-lg border p-4", children: _jsxs("div", { className: "flex items-start gap-3", children: [_jsx(AlertTriangle, { className: "text-feedback-orange mt-0.5 h-5 w-5 shrink-0" }), _jsxs("div", { className: "flex-1", children: [_jsx("p", { className: "text-feedback-orange mb-1 text-sm font-semibold", children: "Remove secret protection?" }), _jsx("p", { className: "text-feedback-orange mb-3 text-xs leading-relaxed", children: "Reviewers will no longer need to enter a secret to access this review." }), _jsxs("div", { className: "flex gap-2", children: [_jsx(Button, { type: "button", variant: "outline", size: "sm", onClick: () => {
                                                                                        setShowRemoveConfirm(false);
                                                                                    }, className: "flex-1", children: "Cancel" }), _jsx(Button, { type: "button", variant: "destructive", size: "sm", onClick: async () => {
                                                                                        // Remove secret immediately
                                                                                        setLoading(true);
                                                                                        try {
                                                                                            const languages = languageMode === "all"
                                                                                                ? ["*"]
                                                                                                : languageMode === "multiple"
                                                                                                    ? selectedLanguages
                                                                                                    : [language];
                                                                                            await updateReviewSettings(review.reviewId, languages, undefined, updateWorkflowOnCompletion, parseInt(requiredApprovals, 10), true, // removeSecret
                                                                                            shareCommentsAndSuggestions);
                                                                                            onUpdated();
                                                                                            onOpenChange(false);
                                                                                        }
                                                                                        catch (err) {
                                                                                            setError(err instanceof Error
                                                                                                ? err.message
                                                                                                : "Failed to remove secret");
                                                                                        }
                                                                                        finally {
                                                                                            setLoading(false);
                                                                                        }
                                                                                    }, disabled: loading, className: "flex-1", children: loading ? (_jsxs(_Fragment, { children: [_jsx(Loader2, { className: "mr-2 h-4 w-4 animate-spin" }), "Removing..."] })) : ("Remove Secret") })] })] })] }) })), showSecretFields && (_jsxs("div", { className: "border-border-default bg-neutral-grey-5 flex flex-col gap-3 rounded-lg border p-4", children: [_jsxs("div", { className: "mb-2 flex items-center justify-between", children: [_jsx("span", { className: "text-neutral-grey-100 text-sm font-medium", children: "Enter new secret" }), _jsx(Button, { type: "button", variant: "ghost", size: "sm", onClick: () => {
                                                                            setShowSecretFields(false);
                                                                            setSecret("");
                                                                            setSecretConfirm("");
                                                                        }, className: "h-7 px-2 text-xs", children: "Cancel" })] }), _jsxs("div", { className: "grid grid-cols-2 gap-3", children: [_jsx(Input, { type: "password", placeholder: "Enter secret", value: secret, onChange: (e) => setSecret(e.target.value), autoComplete: "off", className: "bg-white" }), _jsx(Input, { type: "password", placeholder: "Confirm secret", value: secretConfirm, onChange: (e) => setSecretConfirm(e.target.value), autoComplete: "off", className: "bg-white" })] }), showErrors && secret && secret !== secretConfirm && (_jsx("p", { className: "text-destructive text-xs font-medium", children: "Secrets do not match" }))] }))] })) : (
                                            // No secret - show enable option
                                            _jsx("div", { className: "flex flex-col gap-3", children: !showSecretFields ? (_jsx(Button, { type: "button", variant: "outline", size: "sm", onClick: () => {
                                                        setShowSecretFields(true);
                                                        setSecret("");
                                                        setSecretConfirm("");
                                                    }, className: "w-full", children: "Enable Secret Protection" })) : (_jsxs("div", { className: "border-border-default bg-neutral-grey-5 flex flex-col gap-3 rounded-lg border p-4", children: [_jsxs("div", { className: "mb-2 flex items-center justify-between", children: [_jsx("span", { className: "text-neutral-grey-100 text-sm font-medium", children: "Set secret" }), _jsx(Button, { type: "button", variant: "ghost", size: "sm", onClick: () => {
                                                                        setShowSecretFields(false);
                                                                        setSecret("");
                                                                        setSecretConfirm("");
                                                                    }, className: "h-7 px-2 text-xs", children: "Cancel" })] }), _jsxs("div", { className: "grid grid-cols-2 gap-3", children: [_jsx(Input, { type: "password", placeholder: "Enter secret", value: secret, onChange: (e) => setSecret(e.target.value), autoComplete: "off", className: "bg-white" }), _jsx(Input, { type: "password", placeholder: "Confirm secret", value: secretConfirm, onChange: (e) => setSecretConfirm(e.target.value), autoComplete: "off", className: "bg-white" })] }), showErrors && secret && secret !== secretConfirm && (_jsx("p", { className: "text-destructive text-xs font-medium", children: "Secrets do not match" }))] })) }))] }), _jsxs("div", { className: "flex flex-col gap-3", children: [_jsx("label", { htmlFor: "requiredApprovals", className: "text-neutral-grey-100 text-sm font-semibold", children: "Required Approvals" }), _jsxs("div", { className: "flex flex-col gap-2", children: [_jsxs("div", { className: "flex items-center gap-3", children: [_jsx(Input, { id: "requiredApprovals", type: "number", min: "1", value: requiredApprovals, onChange: (e) => setRequiredApprovals(e.target.value), placeholder: "1", className: "w-24 bg-white" }), _jsx("span", { className: "text-muted-foreground text-xs", children: "Number of reviewers that must approve each page" })] }), showErrors &&
                                                        reviewersCount &&
                                                        requiredApprovals &&
                                                        (() => {
                                                            const num = parseInt(requiredApprovals, 10);
                                                            if (isNaN(num) || num < 1) {
                                                                return (_jsx("p", { className: "text-destructive text-xs font-medium", children: "Must be at least 1" }));
                                                            }
                                                            if (num > reviewersCount) {
                                                                return (_jsxs("p", { className: "text-destructive text-xs font-medium", children: ["Cannot exceed number of reviewers (", reviewersCount, ")"] }));
                                                            }
                                                            return null;
                                                        })()] })] }), _jsxs("div", { className: "flex flex-col gap-1.5", children: [_jsxs("div", { className: "flex items-center gap-3", children: [_jsx(Checkbox, { id: "updateWorkflowOnCompletion", checked: updateWorkflowOnCompletion, onCheckedChange: (checked) => setUpdateWorkflowOnCompletion(!!checked), className: "mt-0" }), _jsx(Label, { htmlFor: "updateWorkflowOnCompletion", className: "text-neutral-grey-100 cursor-pointer text-sm leading-none font-semibold", children: "Update workflow state on completion" })] }), _jsx("p", { className: "text-muted-foreground pl-7 text-xs leading-relaxed", children: "When the review is approved, automatically execute the \"Approve\" workflow action on approved item versions" })] }), _jsxs("div", { className: "flex flex-col gap-1.5", children: [_jsxs("div", { className: "flex items-center gap-3", children: [_jsx(Checkbox, { id: "shareCommentsAndSuggestions", checked: shareCommentsAndSuggestions, onCheckedChange: (checked) => setShareCommentsAndSuggestions(!!checked), className: "mt-0" }), _jsx(Label, { htmlFor: "shareCommentsAndSuggestions", className: "text-neutral-grey-100 cursor-pointer text-sm leading-none font-semibold", children: "Share comments and suggestions with all reviewers" })] }), _jsx("p", { className: "text-muted-foreground pl-7 text-xs leading-relaxed", children: "When enabled, all reviewers in this review will be able to see comments and suggestions made by other reviewers or sitecore users. This will also affect already existing comments." })] }), error && (_jsx("div", { className: "bg-destructive/10 border-destructive/20 text-destructive rounded-lg border p-4 text-sm font-medium", children: error }))] }) }), _jsxs(DialogButtons, { hideBorder: true, className: "bg-neutral-grey-5/50", children: [_jsx(Button, { variant: "ghost", onClick: () => onOpenChange(false), children: "Cancel" }), _jsx(Button, { onClick: handleSave, disabled: loading, className: "min-w-[120px]", children: loading ? (_jsxs(_Fragment, { children: [_jsx(Loader2, { className: "mr-2 h-4 w-4 animate-spin" }), "Saving..."] })) : ("Save Changes") })] })] })] }) }));
}
//# sourceMappingURL=EditReviewSettingsDialog.js.map