import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useState, useEffect, useMemo } from "react";
import { Dialog, DialogContent } from "../../components/ui/dialog";
import { StyledDialogTitle } from "../../components/ui/styled-dialog-title";
import { Button } from "../../components/ui/button";
import { Loader2, ClipboardCheck, MailCheck, CheckCircle2 } from "lucide-react";
import { useEditContext } from "../client/editContext";
import DialogButtons from "../ui/DialogButtons";
import { CreateReviewDetailsStep } from "./CreateReviewDetailsStep";
import { CreateReviewConfirmStep } from "./CreateReviewConfirmStep";
import { CreateReviewSuccessStep } from "./CreateReviewSuccessStep";
import { loadAiProfiles } from "../services/aiService";
import { awaitAgentResponse, closeAgent, startAgent, } from "../services/agentService";
const REVIEW_TITLE_SUGGESTION_TIMEOUT_MS = 12000;
function withTimeout(promise, timeoutMs, timeoutMessage) {
    let timeoutId = null;
    const timeoutPromise = new Promise((_, reject) => {
        timeoutId = setTimeout(() => reject(new Error(timeoutMessage)), timeoutMs);
    });
    return Promise.race([promise, timeoutPromise]).finally(() => {
        if (timeoutId)
            clearTimeout(timeoutId);
    });
}
export function CreateReviewDialog({ open, onOpenChange, onCreated, initialItems, }) {
    const editContext = useEditContext();
    const [step, setStep] = useState("details");
    const [title, setTitle] = useState("");
    const [language, setLanguage] = useState(editContext?.currentItemDescriptor?.language || "en");
    const [languageMode, setLanguageMode] = useState("single");
    const [selectedLanguages, setSelectedLanguages] = useState([
        editContext?.currentItemDescriptor?.language || "en",
    ]);
    const [reviewers, setReviewers] = useState([]);
    const [newReviewer, setNewReviewer] = useState({
        name: "",
        email: "",
    });
    const [items, setItems] = useState([]);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(null);
    const [showErrors, setShowErrors] = useState(false);
    const [expirationDays, setExpirationDays] = useState("");
    const [secret, setSecret] = useState("");
    const [secretConfirm, setSecretConfirm] = useState("");
    const [showSecretFields, setShowSecretFields] = useState(false);
    const [requiredApprovals, setRequiredApprovals] = useState("1");
    const [updateWorkflowOnCompletion, setUpdateWorkflowOnCompletion] = useState(false);
    const [shareCommentsAndSuggestions, setShareCommentsAndSuggestions] = useState(false);
    const [selectedInTree, setSelectedInTree] = useState([]);
    const [selectedFromList, setSelectedFromList] = useState([]);
    const [advancedSettingsOpen, setAdvancedSettingsOpen] = useState(false);
    const [createdReviewId, setCreatedReviewId] = useState(null);
    const [sentInvitationCount, setSentInvitationCount] = useState(0);
    const [sentInvitationEmails, setSentInvitationEmails] = useState([]);
    const [isGeneratingTitle, setIsGeneratingTitle] = useState(false);
    const CONTENT_ROOT_ID = "0de95ae4-41ab-4d01-9eb0-67441b7c2450"; // /sitecore/content
    // Memoize rootItemIds to prevent unnecessary re-renders of ContentTree
    const rootItemIds = useMemo(() => [CONTENT_ROOT_ID], []);
    // Memoize itemIds to prevent unnecessary re-fetches of reviewers
    // This ensures the array reference only changes when items actually change,
    // not on every render (e.g., when typing in the Review Name field)
    const itemIds = useMemo(() => items.map((item) => item.descriptor.id), [items]);
    // Compute form validity for enabling/disabling the Create Review button
    const isFormValid = useMemo(() => {
        // Must have at least one item
        if (items.length === 0)
            return false;
        // Must have at least one reviewer
        if (reviewers.length === 0)
            return false;
        // Validate language selection based on mode
        if (languageMode === "single" && !language)
            return false;
        if (languageMode === "multiple" && selectedLanguages.length === 0)
            return false;
        // Validate secret confirmation
        if (showSecretFields && secret !== secretConfirm)
            return false;
        // Validate requiredApprovals
        const requiredApprovalsNum = requiredApprovals
            ? parseInt(requiredApprovals, 10)
            : 1;
        if (isNaN(requiredApprovalsNum) || requiredApprovalsNum < 1)
            return false;
        if (requiredApprovalsNum > reviewers.length)
            return false;
        return true;
    }, [
        items.length,
        reviewers.length,
        languageMode,
        language,
        selectedLanguages.length,
        showSecretFields,
        secret,
        secretConfirm,
        requiredApprovals,
    ]);
    useEffect(() => {
        if (open && editContext?.currentItemDescriptor && items.length === 0) {
            // Initialize with current page if available - but only if items haven't been set yet
            // This prevents resetting user changes (like includeSubitems toggles) when context changes
            const initializeItems = async () => {
                let currentDescriptor = editContext.currentItemDescriptor;
                // If the descriptor is missing name, display name, or path, fetch it from the server
                if ((!currentDescriptor.name ||
                    !currentDescriptor.displayName ||
                    !currentDescriptor.path) &&
                    editContext.itemsRepository) {
                    try {
                        const stubs = await editContext.itemsRepository.getItemsStubs([
                            currentDescriptor,
                        ]);
                        if (stubs.length > 0 && stubs[0]) {
                            currentDescriptor = {
                                ...currentDescriptor,
                                name: stubs[0].name || currentDescriptor.name,
                                displayName: stubs[0].displayName || currentDescriptor.displayName,
                                path: stubs[0].path || currentDescriptor.path,
                            };
                        }
                    }
                    catch (error) {
                        console.error("Failed to fetch item stub:", error);
                    }
                }
                let itemsToSet;
                if (initialItems) {
                    // Fetch missing names/display names/paths for initial items as well
                    const itemsToFetch = initialItems.filter((i) => !i.name || !i.displayName || !i.path);
                    if (itemsToFetch.length > 0 && editContext.itemsRepository) {
                        try {
                            const stubs = await editContext.itemsRepository.getItemsStubs(itemsToFetch);
                            const stubMap = new Map(stubs.map((s) => [s.id, s]));
                            itemsToSet = initialItems.map((i) => {
                                const stub = stubMap.get(i.id);
                                return {
                                    descriptor: {
                                        ...i,
                                        name: stub?.name || i.name,
                                        displayName: stub?.displayName || i.displayName,
                                        path: stub?.path || i.path,
                                    },
                                    includeSubitems: false,
                                };
                            });
                        }
                        catch (error) {
                            console.error("Failed to fetch item stubs:", error);
                            itemsToSet = initialItems.map((i) => ({
                                descriptor: i,
                                includeSubitems: false,
                            }));
                        }
                    }
                    else {
                        itemsToSet = initialItems.map((i) => ({
                            descriptor: i,
                            includeSubitems: false,
                        }));
                    }
                }
                else {
                    itemsToSet = [
                        {
                            descriptor: currentDescriptor,
                            includeSubitems: false,
                        },
                    ];
                }
                setItems(itemsToSet);
                setLanguage(currentDescriptor.language || "en");
            };
            initializeItems();
        }
    }, [
        open,
        editContext?.currentItemDescriptor,
        editContext?.itemsRepository,
        initialItems,
    ]);
    const isValidEmail = (email) => {
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        return emailRegex.test(email);
    };
    const extractReviewTitleFromAgentResponse = (content) => {
        if (!content)
            return "";
        const fencedTitleMatch = content.match(/```(?:suggestion|title)\s*\n([\s\S]*?)```/i);
        const fencedGenericMatch = content.match(/```\s*\n([\s\S]*?)```/);
        const raw = (fencedTitleMatch?.[1] || fencedGenericMatch?.[1] || content)
            .trim()
            .replace(/^["']|["']$/g, "");
        if (!raw)
            return "";
        return raw.split("\n")[0]?.trim() || "";
    };
    const buildReviewTitleSuggestionPrompt = () => {
        const languageScope = languageMode === "all"
            ? "all languages"
            : languageMode === "multiple"
                ? selectedLanguages.join(", ")
                : language;
        const itemNames = items
            .slice(0, 5)
            .map((item) => item.descriptor.displayName ||
            item.descriptor.name ||
            item.descriptor.path ||
            item.descriptor.id)
            .filter(Boolean)
            .join(", ");
        const reviewerNames = reviewers
            .slice(0, 3)
            .map((reviewer) => reviewer.name || reviewer.email)
            .filter(Boolean)
            .join(", ");
        return `Generate a concise review name for a Sitecore content review.

Context:
- Language scope: ${languageScope}
- Items: ${itemNames || "N/A"}
- Number of reviewers: ${reviewers.length}
- First reviewers: ${reviewerNames || "N/A"}
- Includes subitems: ${items.some((x) => x.includeSubitems) ? "yes" : "no"}

Rules:
- Return a short, clear title (4-10 words).
- Do not use quotes.
- Do not include prefixes like "Review:".
- Output ONLY the title inside a \`\`\`suggestion fenced code block.

Example:
\`\`\`suggestion
Homepage and Navigation Content Review
\`\`\``;
    };
    const generateReviewTitleSuggestion = async () => {
        if (title.trim())
            return null;
        if (!editContext?.addSocketMessageListener || !editContext.sessionId) {
            return null;
        }
        const newAgentId = crypto.randomUUID();
        setIsGeneratingTitle(true);
        try {
            const profiles = await withTimeout(loadAiProfiles(editContext.currentItemDescriptor), REVIEW_TITLE_SUGGESTION_TIMEOUT_MS, "Timed out while loading AI profiles");
            if (!profiles || profiles.length === 0) {
                return null;
            }
            const configuredProfileId = editContext.parheliaSettings?.commentResolveProfileId;
            const selectedProfile = profiles.find((profile) => configuredProfileId &&
                profile.id.toLowerCase() === configuredProfileId.toLowerCase()) || profiles[0];
            if (!selectedProfile)
                return null;
            await withTimeout(startAgent({
                agentId: newAgentId,
                message: buildReviewTitleSuggestionPrompt(),
                sessionId: editContext.sessionId,
                profileId: selectedProfile.id,
                mode: "autonomous",
                context: {
                    items: items.map((item) => ({
                        id: item.descriptor.id,
                        language: item.descriptor.language,
                        version: item.descriptor.version,
                        name: item.descriptor.name,
                        path: item.descriptor.path,
                    })),
                    additionalData: {
                        intent: "review-title-suggestion",
                        reviewerCount: reviewers.length,
                    },
                },
            }), REVIEW_TITLE_SUGGESTION_TIMEOUT_MS, "Timed out while starting title suggestion agent");
            const result = await awaitAgentResponse({
                agentId: newAgentId,
                addSocketMessageListener: editContext.addSocketMessageListener,
                timeout: REVIEW_TITLE_SUGGESTION_TIMEOUT_MS,
            });
            if (!result.success)
                return null;
            const extractedTitle = extractReviewTitleFromAgentResponse(result.content);
            return extractedTitle || null;
        }
        catch (err) {
            console.error("Failed to generate review title suggestion:", err);
            return null;
        }
        finally {
            setIsGeneratingTitle(false);
            try {
                await closeAgent(newAgentId);
            }
            catch (err) {
                console.error("Failed to close review title suggestion agent:", err);
            }
        }
    };
    const emailAlreadyExists = (email) => {
        return reviewers.some((r) => r.email.toLowerCase() === email.toLowerCase());
    };
    const addReviewer = () => {
        if (!newReviewer.name || !newReviewer.email) {
            setShowErrors(true);
            return;
        }
        if (!isValidEmail(newReviewer.email)) {
            setShowErrors(true);
            return;
        }
        if (emailAlreadyExists(newReviewer.email)) {
            setShowErrors(true);
            return;
        }
        setReviewers([...reviewers, { ...newReviewer }]);
        setNewReviewer({ name: "", email: "" });
        setShowErrors(false);
    };
    const removeReviewer = (index) => {
        setReviewers(reviewers.filter((_, i) => i !== index));
    };
    const toggleSubitems = (index) => {
        setItems(items.map((item, i) => i === index
            ? { ...item, includeSubitems: !item.includeSubitems }
            : item));
    };
    const removeItem = (index) => {
        setItems(items.filter((_, i) => i !== index));
    };
    const resetDialogState = () => {
        setStep("details");
        setTitle("");
        setReviewers([]);
        setItems([]);
        setExpirationDays("");
        setSecret("");
        setSecretConfirm("");
        setShowSecretFields(false);
        setRequiredApprovals("1");
        setUpdateWorkflowOnCompletion(false);
        setShareCommentsAndSuggestions(false);
        setShowErrors(false);
        setError(null);
        setLanguageMode("single");
        setSelectedLanguages([
            editContext?.currentItemDescriptor?.language || "en",
        ]);
        setLanguage(editContext?.currentItemDescriptor?.language || "en");
        setAdvancedSettingsOpen(false);
        setSelectedInTree([]);
        setSelectedFromList([]);
        setNewReviewer({ name: "", email: "" });
        setCreatedReviewId(null);
        setSentInvitationCount(0);
        setSentInvitationEmails([]);
        setIsGeneratingTitle(false);
    };
    const validateForm = () => {
        if (items.length === 0) {
            return "Please select at least one page/item";
        }
        if (reviewers.length === 0) {
            return "Please add at least one reviewer";
        }
        if (languageMode === "single" && !language) {
            return "Language is required";
        }
        if (languageMode === "multiple" && selectedLanguages.length === 0) {
            return "Please select at least one language";
        }
        if (showSecretFields && secret !== secretConfirm) {
            return "Secrets do not match";
        }
        const requiredApprovalsNum = requiredApprovals
            ? parseInt(requiredApprovals, 10)
            : 1;
        if (isNaN(requiredApprovalsNum) || requiredApprovalsNum < 1) {
            return "Required Approvals must be at least 1";
        }
        if (requiredApprovalsNum > reviewers.length) {
            return `Required Approvals (${requiredApprovalsNum}) cannot exceed the number of reviewers (${reviewers.length})`;
        }
        return null;
    };
    const handleProceedToConfirm = async () => {
        setShowErrors(true);
        setError(null);
        const validationError = validateForm();
        if (validationError) {
            setError(validationError);
            return;
        }
        setStep("confirm");
        if (!title.trim()) {
            void (async () => {
                const suggestedTitle = await generateReviewTitleSuggestion();
                if (suggestedTitle) {
                    setTitle((currentTitle) => currentTitle.trim() ? currentTitle : suggestedTitle);
                }
            })();
        }
    };
    const handleCreate = async () => {
        setShowErrors(true);
        setError(null);
        const validationError = validateForm();
        if (validationError) {
            setError(validationError);
            return;
        }
        setLoading(true);
        try {
            // Calculate expiration date if specified
            let expirationUtc;
            if (expirationDays &&
                !isNaN(Number(expirationDays)) &&
                Number(expirationDays) > 0) {
                const expirationDate = new Date();
                expirationDate.setDate(expirationDate.getDate() + Number(expirationDays));
                expirationUtc = expirationDate.toISOString();
            }
            // Build languages array based on mode
            let languages;
            if (languageMode === "all") {
                languages = ["*"];
            }
            else if (languageMode === "multiple") {
                languages = selectedLanguages;
            }
            else {
                languages = [language];
            }
            const requiredApprovalsNum = requiredApprovals
                ? parseInt(requiredApprovals, 10)
                : 1;
            const request = {
                title: title || undefined,
                languages,
                reviewers,
                items,
                expirationUtc,
                secret: showSecretFields && secret ? secret : undefined,
                requiredApprovals: requiredApprovalsNum,
                updateWorkflowOnCompletion: updateWorkflowOnCompletion,
                shareCommentsAndSuggestions: shareCommentsAndSuggestions,
            };
            const { createReview, getReviewStatus, sendInvitations } = await import("../services/reviewsService");
            const result = await createReview(request);
            if (result.data?.reviewId) {
                setCreatedReviewId(result.data.reviewId);
                // Get assignments to send invitations
                const statusResult = await getReviewStatus(result.data.reviewId);
                if (statusResult.data?.assignments) {
                    const assignmentsToInvite = statusResult.data.assignments.filter((a) => !a.invitationSentDate);
                    const assignmentIds = assignmentsToInvite.map((a) => a.assignmentId);
                    const reviewerEmails = Array.from(new Set(assignmentsToInvite.map((a) => a.reviewerEmail)));
                    if (assignmentIds.length > 0) {
                        const invitationResult = await sendInvitations(assignmentIds);
                        if (invitationResult.type !== "success") {
                            throw new Error(invitationResult.details ||
                                invitationResult.summary ||
                                "Failed to send invitation emails");
                        }
                        if (invitationResult.data &&
                            typeof invitationResult.data === "object" &&
                            "errors" in invitationResult.data &&
                            Array.isArray(invitationResult.data.errors) &&
                            invitationResult.data.errors.length > 0) {
                            const errorMessages = invitationResult.data.errors
                                .map((err) => err?.message || String(err))
                                .join("; ");
                            throw new Error(errorMessages || "Failed to send invitation emails");
                        }
                    }
                    setSentInvitationCount(assignmentIds.length);
                    setSentInvitationEmails(reviewerEmails);
                }
                else {
                    setSentInvitationCount(0);
                    setSentInvitationEmails([]);
                }
                setStep("success");
            }
            else {
                setError("Failed to create review");
            }
        }
        catch (err) {
            setError(err instanceof Error ? err.message : "Failed to create review");
        }
        finally {
            setLoading(false);
        }
    };
    const addToList = async (itemsToAdd) => {
        const newItems = [...items];
        const sourceItems = itemsToAdd ?? selectedInTree;
        const nodesToAdd = sourceItems.filter((node) => !newItems.some((x) => x.descriptor.id === node.id));
        // Fetch missing paths/names/display names if needed
        const nodesNeedingFetch = nodesToAdd.filter((node) => !node.path || !node.name || !node.displayName);
        if (nodesNeedingFetch.length > 0 && editContext?.itemsRepository) {
            try {
                const descriptorsToFetch = nodesNeedingFetch.map((node) => ({
                    id: node.id,
                    language: node.language || language,
                    version: node.version || 1,
                }));
                const stubs = await editContext.itemsRepository.getItemsStubs(descriptorsToFetch);
                const stubMap = new Map(stubs.map((s) => [s.id, s]));
                nodesToAdd.forEach((node) => {
                    const stub = stubMap.get(node.id);
                    newItems.push({
                        descriptor: {
                            id: node.id,
                            language: node.language || language,
                            version: node.version || 1,
                            name: stub?.name || node.name || "",
                            displayName: stub?.displayName || node.displayName || "",
                            path: stub?.path || node.path || node.idPath || "",
                        },
                        includeSubitems: false,
                    });
                });
            }
            catch (error) {
                console.error("Failed to fetch item stubs:", error);
                // Fallback: add items without fetching
                nodesToAdd.forEach((node) => {
                    newItems.push({
                        descriptor: {
                            id: node.id,
                            language: node.language || language,
                            version: node.version || 1,
                            name: node.name || "",
                            displayName: node.displayName || "",
                            path: node.path || node.idPath || "",
                        },
                        includeSubitems: false,
                    });
                });
            }
        }
        else {
            // No fetch needed, add directly
            nodesToAdd.forEach((node) => {
                newItems.push({
                    descriptor: {
                        id: node.id,
                        language: node.language || language,
                        version: node.version || 1,
                        name: node.name || "",
                        displayName: node.displayName || "",
                        path: node.path || node.idPath || "",
                    },
                    includeSubitems: false,
                });
            });
        }
        setItems(newItems);
        setSelectedInTree([]);
    };
    const removeFromList = () => {
        const idsToRemove = new Set(selectedFromList.map((i) => i.descriptor.id));
        setItems(items.filter((x) => !idsToRemove.has(x.descriptor.id)));
        setSelectedFromList([]);
    };
    const handleAddItem = async (item) => {
        const exists = items.some((x) => x.descriptor.id === item.id);
        if (!exists) {
            let itemDescriptor = {
                id: item.id,
                language: item.language || language,
                version: item.version || 1,
                name: item.name || "",
                displayName: item.displayName || "",
                path: item.path || item.idPath || "",
            };
            // Fetch missing path/name/display name if needed
            if ((!item.path || !item.name || !item.displayName) &&
                editContext?.itemsRepository) {
                try {
                    const stubs = await editContext.itemsRepository.getItemsStubs([
                        {
                            id: item.id,
                            language: item.language || language,
                            version: item.version || 1,
                        },
                    ]);
                    if (stubs.length > 0 && stubs[0]) {
                        itemDescriptor = {
                            ...itemDescriptor,
                            name: stubs[0].name || itemDescriptor.name || "",
                            displayName: stubs[0].displayName || itemDescriptor.displayName || "",
                            path: stubs[0].path || itemDescriptor.path || "",
                        };
                    }
                }
                catch (error) {
                    console.error("Failed to fetch item stub:", error);
                }
            }
            setItems([
                ...items,
                {
                    descriptor: itemDescriptor,
                    includeSubitems: false,
                },
            ]);
        }
    };
    const handleDialogCancel = () => {
        if (loading)
            return;
        resetDialogState();
        onOpenChange(false);
    };
    const handleDialogOpenChange = (nextOpen) => {
        if (!nextOpen) {
            handleDialogCancel();
            return;
        }
        onOpenChange(nextOpen);
    };
    const handleDone = () => {
        const reviewId = createdReviewId;
        resetDialogState();
        onCreated(reviewId);
    };
    const languageSummary = languageMode === "all"
        ? "All languages"
        : languageMode === "multiple"
            ? `${selectedLanguages.length} selected (${selectedLanguages.join(", ")})`
            : language;
    return (_jsx(Dialog, { open: open, onOpenChange: handleDialogOpenChange, children: _jsxs(DialogContent, { className: "flex max-w-5xl overflow-hidden border-none p-0 shadow-2xl", style: { height: "90vh", maxHeight: "90vh" }, children: [_jsx(StyledDialogTitle, { icon: step === "success" ? (_jsx(CheckCircle2, { strokeWidth: 1 })) : step === "confirm" ? (_jsx(MailCheck, { strokeWidth: 1 })) : (_jsx(ClipboardCheck, { strokeWidth: 1 })), title: step === "success"
                        ? "Review Created"
                        : step === "confirm"
                            ? "Confirm Review"
                            : "Create Review" }), _jsxs("div", { className: "flex min-h-0 flex-1 flex-col overflow-hidden", children: [_jsxs("div", { className: "flex min-h-0 flex-1 flex-col overflow-y-auto px-6 pb-4", children: [step === "details" && (_jsx(CreateReviewDetailsStep, { items: items, setItems: setItems, showErrors: showErrors, language: language, setLanguage: setLanguage, rootItemIds: rootItemIds, selectedInTree: selectedInTree, setSelectedInTree: setSelectedInTree, selectedFromList: selectedFromList, setSelectedFromList: setSelectedFromList, addToList: addToList, removeFromList: removeFromList, handleAddItem: handleAddItem, removeItem: removeItem, toggleSubitems: toggleSubitems, reviewers: reviewers, setReviewers: setReviewers, newReviewer: newReviewer, setNewReviewer: setNewReviewer, addReviewer: addReviewer, removeReviewer: removeReviewer, isValidEmail: isValidEmail, emailAlreadyExists: emailAlreadyExists, itemIds: itemIds, languageMode: languageMode, setLanguageMode: setLanguageMode, selectedLanguages: selectedLanguages, setSelectedLanguages: setSelectedLanguages, itemLanguages: editContext?.itemLanguages || [], advancedSettingsOpen: advancedSettingsOpen, setAdvancedSettingsOpen: setAdvancedSettingsOpen, requiredApprovals: requiredApprovals, setRequiredApprovals: setRequiredApprovals, updateWorkflowOnCompletion: updateWorkflowOnCompletion, setUpdateWorkflowOnCompletion: setUpdateWorkflowOnCompletion, shareCommentsAndSuggestions: shareCommentsAndSuggestions, setShareCommentsAndSuggestions: setShareCommentsAndSuggestions, expirationDays: expirationDays, setExpirationDays: setExpirationDays, showSecretFields: showSecretFields, setShowSecretFields: setShowSecretFields, secret: secret, setSecret: setSecret, secretConfirm: secretConfirm, setSecretConfirm: setSecretConfirm, error: error })), step === "confirm" && (_jsx(CreateReviewConfirmStep, { title: title, setTitle: setTitle, isGeneratingTitle: isGeneratingTitle, languageSummary: languageSummary, reviewers: reviewers, items: items, requiredApprovals: requiredApprovals, updateWorkflowOnCompletion: updateWorkflowOnCompletion, expirationDays: expirationDays, showSecretFields: showSecretFields, error: error })), step === "success" && (_jsx(CreateReviewSuccessStep, { sentInvitationCount: sentInvitationCount, sentInvitationEmails: sentInvitationEmails }))] }), _jsxs(DialogButtons, { hideBorder: true, className: "bg-gray-50/50", children: [step === "details" && (_jsxs(_Fragment, { children: [_jsx(Button, { variant: "ghost", onClick: handleDialogCancel, children: "Cancel" }), _jsx(Button, { "data-testid": "create-review-submit-button", onClick: handleProceedToConfirm, disabled: loading || !isFormValid, className: "min-w-[140px] shadow-sm", children: "Continue" })] })), step === "confirm" && (_jsxs(_Fragment, { children: [_jsx(Button, { variant: "ghost", onClick: () => {
                                                setError(null);
                                                setStep("details");
                                            }, disabled: loading, children: "Back" }), _jsx(Button, { "data-testid": "create-review-submit-button", onClick: handleCreate, disabled: loading, className: "min-w-[160px] shadow-sm", children: loading ? (_jsxs(_Fragment, { children: [_jsx(Loader2, { className: "mr-2 h-4 w-4 animate-spin" }), "Creating..."] })) : ("Create & Send Emails") })] })), step === "success" && (_jsx(Button, { onClick: handleDone, className: "min-w-[120px] shadow-sm", children: "Done" }))] })] })] }) }));
}
//# sourceMappingURL=CreateReviewDialog.js.map