import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useEffect, useRef, useState } from "react";
import { CountBadge } from "../../components/ui/badge";
import { Button } from "../../components/ui/button";
import { Input } from "../../components/ui/input";
import { ChevronLeft, Loader2, Lock, Settings } from "lucide-react";
import { loadAiProfiles } from "../services/aiService";
import { unlockReview } from "../services/reviewsService";
import { formatDate } from "../utils";
import { useEditContext } from "../client/editContext";
import { WatchButton } from "../notifications/WatchButton";
import { EditReviewSettingsDialog } from "./EditReviewSettingsDialog";
import { ReviewItemsPanel } from "./ReviewItemsPanel";
import { ReviewersPanel } from "./ReviewersPanel";
import { SimpleTabs } from "../ui/SimpleTabs";
function ReviewBackButton({ onBack, title, action, }) {
    return (_jsxs("div", { className: "border-border-default flex shrink-0 items-center gap-1 border-b px-3 py-1 shadow-xs", children: [_jsx(Button, { variant: "ghost", size: "iconSm", onClick: onBack, "data-testid": "review-detail-back-button", "aria-label": "Back to reviews", children: _jsx(ChevronLeft, { className: "h-5 w-5", strokeWidth: 1 }) }), title && (_jsx("h2", { "data-testid": "review-detail-title", className: "text-neutral-grey-100 min-w-0 flex-1 truncate text-sm font-medium", children: title })), action && (_jsx("div", { className: "border-border-default ml-auto flex shrink-0 items-center border-l pl-1", children: action }))] }));
}
function getLanguageLabel(language) {
    if (language === "*")
        return "All languages";
    if (language === "mixed")
        return "Multiple languages";
    return language;
}
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 [activeTab, setActiveTab] = useState(0);
    const agentLaunchedRef = useRef(null);
    useEffect(() => {
        if (reviewId && !multiReview.reviewDetail) {
            multiReview.setSelectedReviewId(reviewId);
        }
        if (agentLaunchedRef.current !== reviewId) {
            agentLaunchedRef.current = null;
        }
    }, [reviewId, multiReview]);
    useEffect(() => {
        const launchAgentForReview = async () => {
            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;
            const isPreviewUser = editContext?.user?.isLimitedPreviewUser ?? false;
            if (items.length === 0 ||
                (requiresSecret && !secretValidated) ||
                !isPreviewUser) {
                return;
            }
            try {
                const profiles = await loadAiProfiles();
                const firstProfile = profiles?.[0];
                if (!firstProfile)
                    return;
                editContext?.setShowAgentsPanel?.(true);
                const metadata = {
                    items: items.map((item) => ({
                        id: item.itemId,
                        language: item.language,
                        version: 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)}`,
                    },
                };
                setTimeout(() => {
                    window.dispatchEvent(new CustomEvent("editor:addNewAgent", {
                        detail: { metadata },
                    }));
                    agentLaunchedRef.current = reviewId;
                }, 100);
            }
            catch (error) {
                console.error("Failed to launch agent for review:", error);
            }
        };
        void launchAgentForReview();
    }, [reviewId, multiReview.reviewDetail, editContext]);
    if (multiReview.loading && !multiReview.reviewDetail) {
        return (_jsx("div", { className: "flex h-full items-center justify-center", children: _jsx(Loader2, { strokeWidth: 1, className: "text-neutral-grey-50 h-7 w-7 animate-spin" }) }));
    }
    if (multiReview.error && !multiReview.reviewDetail) {
        return (_jsxs("div", { className: "flex h-full flex-col", children: [_jsx(ReviewBackButton, { onBack: onBack }), _jsx("div", { className: "flex flex-1 items-center justify-center p-4", children: _jsx("div", { className: "bg-feedback-red-light text-feedback-red rounded-lg p-4 text-sm", children: multiReview.error }) })] }));
    }
    if (!multiReview.reviewDetail) {
        return (_jsxs("div", { className: "flex h-full flex-col", children: [_jsx(ReviewBackButton, { onBack: onBack }), _jsx("div", { className: "text-neutral-grey-50 flex flex-1 items-center justify-center text-sm", children: "Review not found" })] }));
    }
    const { review, assignments, items } = multiReview.reviewDetail;
    const itemIds = items.map((item) => item.itemId);
    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;
    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) {
                await multiReview.refreshReviewDetail?.();
                setSecret("");
                agentLaunchedRef.current = null;
            }
            else if (result.data?.expired) {
                setUnlockError("This review has expired");
            }
            else {
                setUnlockError("Invalid secret. Please try again.");
            }
        }
        catch (error) {
            setUnlockError(error instanceof Error ? error.message : "Failed to unlock review");
        }
        finally {
            setUnlocking(false);
        }
    };
    if (needsUnlock) {
        return (_jsxs("div", { className: "flex h-full flex-col", children: [_jsx(ReviewBackButton, { onBack: onBack }), _jsx("div", { className: "flex flex-1 items-center justify-center", children: _jsxs("div", { className: "flex w-full max-w-sm flex-col items-center gap-4 p-6", children: [_jsx(Lock, { className: "text-neutral-grey-50 h-10 w-10", strokeWidth: 1 }), _jsx("h2", { "data-testid": "review-detail-title", className: "text-neutral-grey-100 text-center text-lg font-medium", children: review.title || `Review ${review.reviewId.slice(0, 8)}` }), _jsx("p", { className: "text-neutral-grey-50 text-center text-xs", children: "Enter the secret provided by the review creator to access this review." }), isExpired ? (_jsx("div", { className: "bg-feedback-red-light text-feedback-red w-full rounded-lg p-3 text-center text-xs", children: "This review has expired and is no longer accessible." })) : (_jsxs(_Fragment, { children: [_jsx(Input, { "data-testid": "unlock-secret-input", type: "password", placeholder: "Enter secret", value: secret, onChange: (event) => {
                                            setSecret(event.target.value);
                                            setUnlockError(null);
                                        }, onKeyDown: (event) => {
                                            if (event.key === "Enter")
                                                void handleUnlock();
                                        }, disabled: unlocking, autoComplete: "off" }), unlockError && (_jsx("div", { "data-testid": "unlock-error-message", className: "text-feedback-red text-xs", children: unlockError })), _jsxs(Button, { "data-testid": "unlock-review-button", onClick: handleUnlock, disabled: unlocking || !secret.trim(), className: "w-full", children: [unlocking && (_jsx(Loader2, { strokeWidth: 1, className: "animate-spin" })), "Unlock review"] })] }))] }) })] }));
    }
    const allReviewersResponded = assignments.length > 0 &&
        assignments.every((assignment) => (assignment.decisions?.length ?? 0) === items.length);
    const isLimitedPreviewUser = editContext?.user?.isLimitedPreviewUser ?? false;
    const isCreator = [editContext?.user?.name, editContext?.user?.fullName].some((identity) => !!identity &&
        review.createdBy.localeCompare(identity, undefined, {
            sensitivity: "accent",
        }) === 0);
    const canEditSettings = !isLimitedPreviewUser &&
        (isCreator || editContext?.user?.isAdministrator === true);
    const reviewTitle = review.title || `Review ${review.reviewId.slice(0, 8)}`;
    const reviewItemsContent = (_jsx("div", { className: "min-h-0 flex-1 overflow-y-auto px-3 py-3", children: _jsx(ReviewItemsPanel, { review: review, items: items, assignments: assignments, onMakeDecision: multiReview.makeItemDecision, loading: multiReview.loading, onSetFinalDecision: (decision) => multiReview.setReviewFinalDecision(reviewId, decision), onAddPages: (pages) => multiReview.addPages(reviewId, pages), allReviewersResponded: allReviewersResponded, selectedReviewerId: selectedReviewerId, onSelectReviewer: setSelectedReviewerId, currentUserEmail: editContext?.user?.email, requiredApprovals: review.requiredApprovals }) }));
    const reviewersContent = (_jsx("div", { className: "min-h-0 flex-1 overflow-y-auto px-3 py-3", children: _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 }) }));
    const detailsContent = (_jsx("div", { className: "min-h-0 flex-1 overflow-y-auto px-3 py-3", children: _jsx("div", { className: "p-3", children: _jsxs("dl", { className: "grid grid-cols-[auto_1fr] gap-x-3 gap-y-2 text-xs", children: [_jsx("dt", { className: "text-neutral-grey-50", children: "Created" }), _jsxs("dd", { className: "text-neutral-grey-100 min-w-0 break-words", children: [formatDate(new Date(review.createdAt)), " by ", review.createdBy] }), _jsx("dt", { className: "text-neutral-grey-50", children: "Language" }), _jsx("dd", { className: "text-neutral-grey-100", children: getLanguageLabel(review.language) })] }) }) }));
    const tabs = [
        {
            id: "review-items-tab",
            label: "Review Items",
            badge: _jsx(CountBadge, { children: items.length }),
            content: reviewItemsContent,
            testId: "review-items-tab",
        },
        ...(!isLimitedPreviewUser
            ? [
                {
                    id: "reviewers-tab",
                    label: "Reviewers",
                    badge: _jsx(CountBadge, { children: assignments.length }),
                    content: reviewersContent,
                    testId: "reviewers-tab",
                },
            ]
            : []),
        {
            id: "review-details-tab",
            label: "Details",
            content: detailsContent,
            testId: "review-details-tab",
        },
    ];
    return (_jsxs("div", { className: "flex h-full flex-col bg-white", children: [_jsx(ReviewBackButton, { onBack: onBack, title: reviewTitle, action: _jsxs(_Fragment, { children: [_jsx(WatchButton, { targetType: "review", targetId: reviewId }), canEditSettings && (_jsx(Button, { variant: "ghost", size: "iconXs", onClick: () => setEditSettingsOpen(true), "data-testid": "review-edit-settings-button", title: "Edit review settings", children: _jsx(Settings, { strokeWidth: 1 }) }))] }) }), _jsx("div", { className: "min-h-0 flex-1", children: _jsx(SimpleTabs, { tabs: tabs, activeTab: activeTab, setActiveTab: setActiveTab, className: "border-border-default mt-1 border-b px-2", testId: "review-detail-tabs" }) }), _jsx(EditReviewSettingsDialog, { open: editSettingsOpen, onOpenChange: setEditSettingsOpen, review: review, items: items, reviewersCount: assignments.length, onUpdated: async () => {
                    await multiReview.refreshReviewDetail?.();
                } })] }));
}
//# sourceMappingURL=ReviewDetail.js.map