import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useEffect, useState, useRef } from "react";
import { ReviewersPanel } from "./ReviewersPanel";
import { DecisionsMatrix } from "./DecisionsMatrix";
import { SimpleToolbar } from "../ui/SimpleToolbar";
import { SimpleIconButton } from "../ui/SimpleIconButton";
import { Splitter } from "../ui/Splitter";
import { ArrowLeft, Loader2, Lock, Settings } from "lucide-react";
import { formatDate } from "../utils";
import { Badge } from "../../components/ui/badge";
import { useEditContext } from "../client/editContext";
import { Button } from "../../components/ui/button";
import { Input } from "../../components/ui/input";
import { unlockReview } from "../services/reviewsService";
import { EditReviewSettingsDialog } from "./EditReviewSettingsDialog";
import { loadAiProfiles } from "../services/aiService";
import { WatchButton } from "../notifications/WatchButton";
export function ReviewDetail({ reviewId, onBack, multiReview, }) {
    const editContext = useEditContext();
    const [selectedReviewerId, setSelectedReviewerId] = useState(null);
    const [secret, setSecret] = useState("");
    const [unlocking, setUnlocking] = useState(false);
    const [unlockError, setUnlockError] = useState(null);
    const [editSettingsOpen, setEditSettingsOpen] = useState(false);
    const agentLaunchedRef = useRef(null);
    useEffect(() => {
        if (reviewId && !multiReview.reviewDetail) {
            multiReview.setSelectedReviewId(reviewId);
        }
        // Reset agent launch flag when review ID changes (not when reviewDetail updates)
        if (agentLaunchedRef.current !== reviewId) {
            agentLaunchedRef.current = null;
        }
    }, [reviewId, multiReview]);
    // Auto-launch agent when review is opened/unlocked
    useEffect(() => {
        const launchAgentForReview = async () => {
            // Only launch once per review ID
            if (agentLaunchedRef.current === reviewId || !multiReview.reviewDetail) {
                return;
            }
            const { review, items } = multiReview.reviewDetail;
            const requiresSecret = multiReview.reviewDetail.requiresSecret ??
                review.requiresSecret ??
                false;
            const secretValidated = multiReview.reviewDetail.secretValidated ?? false;
            // Only launch if review is accessible (no secret required, or secret validated, and items are loaded)
            if (items.length === 0) {
                return; // Items not loaded yet
            }
            if (requiresSecret && !secretValidated) {
                return; // Still needs unlock
            }
            // Check if user is a preview user (review link context)
            const isPreviewUser = editContext?.user?.isLimitedPreviewUser ?? false;
            if (!isPreviewUser) {
                return; // Only auto-launch for preview users accessing via review link
            }
            try {
                // Load available profiles (will be filtered by backend policy)
                const profiles = await loadAiProfiles();
                if (!profiles || profiles.length === 0) {
                    return; // No profiles available
                }
                // Use first available profile
                const firstProfile = profiles[0];
                if (!firstProfile) {
                    return; // No profile available
                }
                // Open agents panel
                editContext?.setShowAgentsPanel?.(true);
                // Create agent metadata with review context
                const metadata = {
                    items: items.map((item) => ({
                        id: item.itemId,
                        language: item.language,
                        version: 0, // Review items don't have version, default to 0
                        name: item.name,
                    })),
                    additionalData: {
                        profileId: firstProfile.id,
                        profileName: firstProfile.name,
                        initialPrompt: `This agent is assisting with review: ${review.title || review.reviewId.slice(0, 8)}`,
                    },
                };
                // Dispatch event to create agent
                setTimeout(() => {
                    try {
                        window.dispatchEvent(new CustomEvent("editor:addNewAgent", {
                            detail: { metadata },
                        }));
                        agentLaunchedRef.current = reviewId;
                    }
                    catch (e) {
                        console.error("Failed to launch agent for review:", e);
                    }
                }, 100);
            }
            catch (error) {
                console.error("Failed to launch agent for review:", error);
            }
        };
        launchAgentForReview();
    }, [reviewId, multiReview.reviewDetail, editContext]);
    if (multiReview.loading && !multiReview.reviewDetail) {
        return (_jsx("div", { className: "flex h-full items-center justify-center", children: _jsx(Loader2, { className: "h-8 w-8 animate-spin" }) }));
    }
    if (multiReview.error && !multiReview.reviewDetail) {
        return (_jsxs("div", { className: "flex h-full flex-col", children: [_jsx(SimpleToolbar, { children: _jsx(SimpleIconButton, { label: "Back", icon: _jsx(ArrowLeft, { className: "h-4 w-4" }), onClick: onBack }) }), _jsx("div", { className: "flex flex-1 items-center justify-center", children: _jsx("div", { className: "rounded bg-red-100 p-4 text-red-700", children: multiReview.error }) })] }));
    }
    if (!multiReview.reviewDetail) {
        return (_jsxs("div", { className: "flex h-full flex-col", children: [_jsx(SimpleToolbar, { children: _jsx(SimpleIconButton, { label: "Back", icon: _jsx(ArrowLeft, { className: "h-4 w-4" }), onClick: onBack }) }), _jsx("div", { className: "flex flex-1 items-center justify-center", children: _jsx("div", { className: "text-gray-500", children: "Review not found" }) })] }));
    }
    const { review, assignments, items } = multiReview.reviewDetail;
    // Extract item IDs for predefined reviewer selector
    const itemIds = items.map((item) => item.itemId);
    // Check if unlock is needed (from the status response, not just review object)
    const requiresSecret = multiReview.reviewDetail.requiresSecret ?? review.requiresSecret ?? false;
    const secretValidated = multiReview.reviewDetail.secretValidated ?? false;
    const isExpired = review.isExpired ?? multiReview.reviewDetail.expired ?? false;
    const needsUnlock = requiresSecret && !secretValidated && items.length === 0;
    const handleUnlock = async () => {
        if (!secret.trim()) {
            setUnlockError("Please enter the secret");
            return;
        }
        setUnlocking(true);
        setUnlockError(null);
        try {
            const result = await unlockReview(reviewId, secret);
            if (result.data?.secretValid) {
                // Refresh the review detail to get the items
                await multiReview.refreshReviewDetail?.();
                setSecret("");
                // Reset agent launch flag so agent can be launched after unlock
                agentLaunchedRef.current = null;
            }
            else if (result.data?.expired) {
                setUnlockError("This review has expired");
            }
            else {
                setUnlockError("Invalid secret. Please try again.");
            }
        }
        catch (err) {
            setUnlockError(err instanceof Error ? err.message : "Failed to unlock review");
        }
        finally {
            setUnlocking(false);
        }
    };
    // Show unlock panel if secret is required and not validated
    if (needsUnlock || (requiresSecret && !secretValidated)) {
        return (_jsxs("div", { className: "flex h-full flex-col", children: [_jsx(SimpleToolbar, { children: _jsx(SimpleIconButton, { label: "Back", icon: _jsx(ArrowLeft, { className: "h-4 w-4" }), onClick: onBack }) }), _jsx("div", { className: "flex flex-1 items-center justify-center", children: _jsxs("div", { className: "flex w-full max-w-md flex-col items-center gap-4 p-8", children: [_jsx(Lock, { className: "h-12 w-12 text-gray-400" }), _jsx("h2", { "data-testid": "review-detail-title", className: "text-xl font-semibold", children: review.title || `Review ${review.reviewId.slice(0, 8)}` }), _jsx("p", { className: "text-center text-sm text-gray-600", children: "This review requires a secret to access. Please enter the secret provided by the review creator." }), isExpired && (_jsx("div", { className: "rounded bg-red-100 p-3 text-sm text-red-700", children: "This review has expired and is no longer accessible." })), !isExpired && (_jsxs(_Fragment, { children: [_jsxs("div", { className: "flex w-full flex-col gap-2", children: [_jsx(Input, { "data-testid": "unlock-secret-input", type: "password", placeholder: "Enter secret", value: secret, onChange: (e) => {
                                                    setSecret(e.target.value);
                                                    setUnlockError(null);
                                                }, onKeyDown: (e) => {
                                                    if (e.key === "Enter") {
                                                        handleUnlock();
                                                    }
                                                }, disabled: unlocking, autoComplete: "off" }), unlockError && (_jsx("div", { "data-testid": "unlock-error-message", className: "text-sm text-red-600", children: unlockError }))] }), _jsx(Button, { "data-testid": "unlock-review-button", onClick: handleUnlock, disabled: unlocking || !secret.trim(), className: "w-full", children: unlocking ? (_jsxs(_Fragment, { children: [_jsx(Loader2, { className: "mr-2 h-4 w-4 animate-spin" }), "Unlocking..."] })) : ("Unlock Review") })] }))] }) })] }));
    }
    const allReviewersResponded = assignments.every((assignment) => {
        const decisionsCount = assignment.decisions?.length || 0;
        return decisionsCount === items.length;
    });
    // Check if current user is the review creator
    const isCreator = review.createdBy === editContext?.user?.name;
    const isLimitedPreviewUser = editContext?.user?.isLimitedPreviewUser ?? false;
    // Build panels array - exclude reviewers panel for limited preview users
    const panels = [
        ...(isLimitedPreviewUser
            ? []
            : [
                {
                    name: "reviewers",
                    defaultSize: 200,
                    content: (_jsx(ReviewersPanel, { assignments: assignments, onAddReviewer: (reviewers) => multiReview.addReviewersToReview(reviewId, reviewers), onRemoveReviewer: (assignmentId) => multiReview.removeReviewerFromReview(assignmentId), onSendInvitations: (assignmentIds) => multiReview.sendReviewInvitations(assignmentIds), loading: multiReview.loading, selectedReviewerId: selectedReviewerId, onSelectReviewer: setSelectedReviewerId, itemIds: itemIds, language: review.language })),
                },
            ]),
        {
            name: "decisions",
            defaultSize: "auto",
            content: (_jsx(DecisionsMatrix, { items: items, assignments: assignments, onMakeDecision: multiReview.makeItemDecision, loading: multiReview.loading, reviewId: reviewId, language: review.language, finalDecision: review.finalDecision, onSetFinalDecision: (decision) => multiReview.setReviewFinalDecision(reviewId, decision), onAddPages: (items) => multiReview.addPages(reviewId, items), onRemovePages: (items) => multiReview.removePages(reviewId, items), allReviewersResponded: allReviewersResponded, selectedReviewerId: selectedReviewerId, onSelectReviewer: setSelectedReviewerId, currentUserEmail: editContext?.user?.email, requiredApprovals: review.requiredApprovals })),
        },
    ];
    return (_jsxs("div", { className: "flex h-full flex-col", children: [_jsx(SimpleToolbar, { children: _jsx(SimpleIconButton, { label: "Back", icon: _jsx(ArrowLeft, { className: "h-4 w-4" }), onClick: onBack }) }), _jsx("div", { className: "border-b p-4", children: _jsxs("div", { className: "flex items-start justify-between", children: [_jsxs("div", { className: "flex-1", children: [_jsx("h2", { "data-testid": "review-detail-title", className: "text-lg font-semibold", children: review.title || `Review ${review.reviewId.slice(0, 8)}` }), _jsxs("div", { className: "mt-2 flex items-center gap-4 text-xs text-gray-500", children: [_jsxs("span", { children: ["Created: ", formatDate(new Date(review.createdAt))] }), _jsxs("span", { children: ["By: ", review.createdBy] }), _jsxs("span", { className: "flex items-center gap-1", children: ["Language:", " ", review.language === "*" ? (_jsx(Badge, { variant: "outline", children: "All Languages" })) : review.language === "mixed" ? (_jsx("span", { children: "Multiple Languages" })) : (review.language)] })] })] }), _jsxs("div", { className: "flex items-center gap-2", children: [_jsx(WatchButton, { targetType: "review", targetId: reviewId }), isCreator && (_jsx(SimpleIconButton, { "data-testid": "review-edit-settings-button", label: "Edit Settings", icon: _jsx(Settings, { className: "h-4 w-4" }), onClick: () => setEditSettingsOpen(true) }))] })] }) }), _jsx(Splitter, { direction: "vertical", localStorageKey: `review-detail-splitter-${reviewId}`, panels: panels }), _jsx(EditReviewSettingsDialog, { open: editSettingsOpen, onOpenChange: setEditSettingsOpen, review: review, items: items, reviewersCount: assignments.length, onUpdated: async () => {
                    // Refresh review detail after settings update
                    await multiReview.refreshReviewDetail?.();
                } })] }));
}
//# sourceMappingURL=ReviewDetail.js.map