import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useState, useEffect } from "react";
import { Dialog, DialogContent } 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, Settings } from "lucide-react";
import { useEditContext } from "../client/editContext";
import { updateReviewSettings } from "../services/reviewsService";
import DialogButtons from "../ui/DialogButtons";
import { StyledDialogTitle } from "../../components/ui/styled-dialog-title";
import { SecretPhraseFields } from "./SecretPhraseInput";
export function EditReviewSettingsDialog({ open, onOpenChange, review, items, reviewersCount, onUpdated, }) {
    const editContext = useEditContext();
    const [selectedLanguages, setSelectedLanguages] = useState([]);
    const [secret, setSecret] = useState("");
    const [secretConfirm, setSecretConfirm] = useState("");
    const [showSecretFields, setShowSecretFields] = 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 [originallyAllLanguages, setOriginallyAllLanguages] = useState(false);
    const availableLanguages = editContext?.itemLanguages || [];
    const availableLanguageCodes = availableLanguages.map((itemLanguage) => itemLanguage.languageCode);
    // Initialize form when dialog opens or review changes
    useEffect(() => {
        if (open && review) {
            let initialLanguages = [];
            const isAllLanguages = review.language === "*";
            if (isAllLanguages) {
                initialLanguages = ["*"];
                setSelectedLanguages((editContext?.itemLanguages || []).map((itemLanguage) => itemLanguage.languageCode));
            }
            else if (review.language === "mixed") {
                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 {
                initialLanguages = [review.language];
                setSelectedLanguages([review.language]);
            }
            setOriginalLanguages(initialLanguages);
            setOriginallyAllLanguages(isAllLanguages);
            // Reset secret fields
            setSecret("");
            setSecretConfirm("");
            setShowSecretFields(review.requiresSecret ?? false);
            setUpdateWorkflowOnCompletion(review.updateWorkflowOnCompletion ?? false);
            setShareCommentsAndSuggestions(review.shareCommentsAndSuggestions ?? false);
            setRequiredApprovals((review.requiredApprovals ?? 1).toString());
            setError(null);
            setShowErrors(false);
        }
    }, [open, review, items, editContext?.itemLanguages]);
    const getLanguagesForSave = () => {
        const selectedLanguageSet = new Set(selectedLanguages);
        const allAvailableLanguagesSelected = availableLanguageCodes.length > 0 &&
            selectedLanguages.length === availableLanguageCodes.length &&
            availableLanguageCodes.every((code) => selectedLanguageSet.has(code));
        return allAvailableLanguagesSelected ? ["*"] : selectedLanguages;
    };
    // Calculate removed languages
    const getRemovedLanguages = () => {
        if (!review)
            return [];
        const currentLanguages = getLanguagesForSave();
        if (originallyAllLanguages && !currentLanguages.includes("*")) {
            return ["*"];
        }
        if (currentLanguages.includes("*") && !originallyAllLanguages) {
            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);
        if (selectedLanguages.length === 0) {
            setError("Please select at least one language");
            return;
        }
        if (showSecretFields && secret !== secretConfirm) {
            setError("Secrets do not match");
            return;
        }
        if (showSecretFields && !review?.requiresSecret && !secret) {
            setError("Please enter a secret phrase");
            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 {
            const languages = getLanguagesForSave();
            // A checked existing secret with blank fields keeps the current value.
            // Unchecking an existing secret removes it when the form is saved.
            const secretToSend = showSecretFields && secret ? secret : undefined;
            const removeSecret = review.requiresSecret && !showSecretFields ? true : undefined;
            const result = await updateReviewSettings(review.reviewId, languages, secretToSend, updateWorkflowOnCompletion, requiredApprovalsNum, removeSecret, shareCommentsAndSuggestions);
            if (result.type !== "success") {
                throw new Error(result.details ||
                    result.summary ||
                    "Failed to update review settings");
            }
            // Success - refresh and close
            await 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(StyledDialogTitle, { icon: _jsx(Settings, { strokeWidth: 1 }), title: "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", children: [_jsxs("div", { className: "flex flex-col gap-4", children: [_jsxs("div", { className: "flex flex-col gap-2 rounded-lg bg-white 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: "Select Languages" }), _jsxs("div", { className: "flex gap-2", children: [_jsx(Button, { type: "button", variant: "ghost", size: "sm", onClick: () => {
                                                                            setSelectedLanguages(availableLanguages.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: availableLanguages.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, { "data-testid": `review-language-checkbox-${lang.languageCode}`, 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" }))] }), 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, { strokeWidth: 1, 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-medium", children: "Removing languages will delete review decisions" }), _jsx("p", { className: "text-feedback-orange text-xs leading-relaxed", children: originallyAllLanguages
                                                                    ? "Selecting 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.";
                                                                    })() })] })] }))] }), _jsx("div", { className: "border-border-default border-t", "data-testid": "settings-section-divider" }), _jsxs("div", { className: "flex items-start gap-4", children: [_jsx(Checkbox, { id: "editHasSecret", "data-testid": "require-secret-checkbox", checked: showSecretFields, onCheckedChange: (checked) => {
                                                    setShowSecretFields(!!checked);
                                                    setSecret("");
                                                    setSecretConfirm("");
                                                }, className: "mt-1" }), _jsxs("div", { className: "flex flex-1 flex-col gap-3", children: [_jsxs("div", { className: "flex flex-col gap-1", children: [_jsx(Label, { htmlFor: "editHasSecret", className: "text-neutral-grey-100 cursor-pointer text-sm leading-tight font-medium", children: "Require secret to unlock" }), _jsx("span", { className: "text-muted-foreground text-xs leading-relaxed", children: "Reviewers must enter a shared secret phrase before they can access and review the content." })] }), showSecretFields && (_jsxs("div", { className: "grid max-w-md grid-cols-2 gap-3", children: [_jsx(SecretPhraseFields, { secret: secret, secretConfirm: secretConfirm, onSecretChange: setSecret, onSecretConfirmChange: setSecretConfirm }), review?.requiresSecret && !secret && !secretConfirm && (_jsx("p", { className: "text-muted-foreground col-span-2 text-xs", children: "Leave both fields blank to keep the current secret." })), secret && secretConfirm && secret !== secretConfirm && (_jsx("p", { className: "text-destructive col-span-2 text-xs font-medium", children: "Secret phrases do not match" }))] }))] })] }), _jsx("div", { className: "border-border-default border-t", "data-testid": "settings-section-divider" }), _jsxs("div", { className: "flex flex-col gap-3 pl-8", children: [_jsx("label", { htmlFor: "requiredApprovals", className: "text-neutral-grey-100 text-sm font-medium", 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;
                                                        })()] })] }), _jsx("div", { className: "border-border-default border-t", "data-testid": "settings-section-divider" }), _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-medium", 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" })] }), _jsx("div", { className: "border-border-default border-t", "data-testid": "settings-section-divider" }), _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-medium", 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, { 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, { strokeWidth: 1, className: "mr-2 h-4 w-4 animate-spin" }), "Saving..."] })) : ("Save Changes") })] })] })] }) }));
}
//# sourceMappingURL=EditReviewSettingsDialog.js.map