import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { RefreshCw, CheckCircle } from "lucide-react";
import { SettingsCard as Card } from "../SettingsCard";
import { DeleteIcon } from "../../../components/ui/delete-icon";
import { cn } from "../../../lib/utils";
import { getRebuildStatus } from "./utils";
/**
 * Displays rebuild index controls and status
 */
export function RebuildIndexSection({ indexStatus, collectionStatus, importStatus, centroidsStatus, queueStatus, providerInfo, stagingStats, stageResult, debouncedCurrentItem, isCollecting, isGenerating, isFinalizing, isCancellingCollection, forceRegenerate, onRebuild, onGenerateEmbeddings, onFinalize, onStopGeneration, onCancelCollection, onForceRegenerateChange, onClearStaging, }) {
    // Get rebuild status
    const rebuildStatus = getRebuildStatus(isCollecting, isGenerating, indexStatus, importStatus, centroidsStatus, collectionStatus, queueStatus, debouncedCurrentItem);
    const batches = indexStatus?.batches || [];
    const completedCount = batches.filter((b) => (b.status || "").toLowerCase() === "completed").length;
    const inProgressCount = batches.filter((b) => {
        const s = (b.status || "").toLowerCase();
        return s === "submitted" || s === "processing" || s === "queued";
    }).length;
    // Check if an operation is in progress
    const operationInProgress = isCollecting ||
        collectionStatus?.isCollecting ||
        isGenerating ||
        inProgressCount > 0 ||
        indexStatus?.rebuilding ||
        importStatus?.isImporting ||
        centroidsStatus?.isPopulating;
    // Rebuild status display
    const rebuildStatusDisplay = rebuildStatus ? (_jsx("div", { className: "bg-neutral-grey-5 rounded p-3", children: _jsxs("div", { className: "space-y-1", children: [_jsxs("div", { className: cn("flex items-center gap-2 text-sm font-medium", rebuildStatus.statusClass), children: [rebuildStatus.showSpinner && (_jsx(RefreshCw, { className: "h-4 w-4 animate-spin", strokeWidth: 1 })), rebuildStatus.statusLabel, ((queueStatus?.isRunning && (queueStatus?.pendingCount ?? 0) > 0) ||
                            importStatus?.isImporting ||
                            isGenerating) && (_jsx("button", { onClick: onStopGeneration, className: "bg-neutral-grey-100 hover:bg-neutral-grey-100 ml-auto shrink-0 rounded px-3 py-1.5 text-sm font-medium text-white", children: "Stop" })), (collectionStatus?.isCollecting || isCollecting) && (_jsx("button", { onClick: onCancelCollection, disabled: isCancellingCollection, className: cn("ml-auto shrink-0 rounded px-3 py-1.5 text-sm font-medium", isCancellingCollection
                                ? "bg-neutral-grey-10 text-neutral-grey-50 cursor-not-allowed"
                                : "bg-neutral-grey-100 hover:bg-neutral-grey-100 text-white"), children: isCancellingCollection ? "Cancelling..." : "Cancel" }))] }), rebuildStatus.progressDetails &&
                    rebuildStatus.progressDetails.length > 0 && (_jsx("div", { className: "text-neutral-grey-50 text-xs", children: rebuildStatus.progressDetails.join(" • ") })), !operationInProgress &&
                    rebuildStatus.errorCount !== undefined &&
                    rebuildStatus.errorCount > 0 && (_jsxs("div", { className: "text-component-shared text-xs", children: [rebuildStatus.errorCount, " error", rebuildStatus.errorCount !== 1 ? "s" : "", rebuildStatus.recentErrors &&
                            rebuildStatus.recentErrors.length > 0 && (_jsxs("details", { className: "mt-1", children: [_jsx("summary", { className: "cursor-pointer hover:underline", children: "Show recent errors" }), _jsx("ul", { className: "mt-1 list-disc space-y-0.5 pl-5", children: rebuildStatus.recentErrors.map((error, idx) => (_jsx("li", { className: "text-xs", children: error }, idx))) })] }))] }))] }) })) : null;
    // Action buttons
    // State machine:
    // 1. collectionStatus.isCollecting → Show collection progress (handled by operationInProgress)
    // 2. pendingCount > 0 && queueProcessor.isRunning → Show generation progress (handled by operationInProgress)
    // 3. pendingCount > 0 && !queueProcessor.isRunning → Show generation buttons (refresh recovery)
    // 4. Otherwise → Show Rebuild button
    const hasPendingItems = (stagingStats?.pendingCount ?? 0) > 0 ||
        (stageResult?.requestCount ?? 0) > 0;
    const queueIsRunning = queueStatus?.isRunning ?? false;
    const actionButtons = (() => {
        if (operationInProgress) {
            return null;
        }
        else if (hasPendingItems && !queueIsRunning) {
            // Show generation options - either from fresh staging or recovered from backend
            const supportsBatch = providerInfo?.supportsBatchApi ?? false;
            // Prefer stagingStats for display, fallback to stageResult
            const pendingCount = stagingStats?.pendingCount ?? stageResult?.requestCount ?? 0;
            const estimatedTokens = stagingStats?.estimatedTokens ?? stageResult?.estimatedInputTokens ?? 0;
            const batchCost = stagingStats?.estimatedBatchCost ??
                stageResult?.estimatedBatchCost ??
                0;
            const directCost = stagingStats?.estimatedDirectCost ??
                stageResult?.estimatedDirectCost ??
                0;
            return (_jsxs("div", { className: "space-y-3", children: [_jsxs("div", { className: "bg-neutral-grey-5 rounded p-3", children: [_jsxs("div", { className: "text-neutral-grey-50 flex items-center justify-between text-sm", children: [_jsx("span", { children: "Pending Requests" }), _jsx("span", { children: pendingCount.toLocaleString() })] }), _jsxs("div", { className: "text-neutral-grey-50 mt-1 flex items-center justify-between text-sm", children: [_jsx("span", { children: "Estimated Input Tokens" }), _jsx("span", { children: estimatedTokens.toLocaleString() })] }), supportsBatch && (_jsxs("div", { className: "text-neutral-grey-50 mt-1 flex items-center justify-between text-sm", children: [_jsx("span", { children: "Estimated Batch Cost" }), _jsxs("span", { children: ["~$", batchCost.toFixed(2)] })] })), _jsxs("div", { className: "text-neutral-grey-50 mt-1 flex items-center justify-between text-sm", children: [_jsx("span", { children: "Estimated Direct Cost" }), _jsxs("span", { children: ["~$", directCost.toFixed(2)] })] })] }), _jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [supportsBatch && (_jsxs("button", { onClick: () => onGenerateEmbeddings("batch"), disabled: isGenerating, className: cn("flex items-center gap-2 rounded px-3 py-1.5 text-sm font-medium transition-colors", {
                                    "bg-feedback-orange hover:bg-feedback-orange cursor-pointer text-white": !isGenerating,
                                    "bg-neutral-grey-10 text-neutral-grey-50 cursor-not-allowed": isGenerating,
                                }), children: [_jsx(CheckCircle, { className: "h-4 w-4", strokeWidth: 1 }), isGenerating
                                        ? "Starting..."
                                        : `Batch (~$${batchCost.toFixed(2)})`] })), _jsxs("button", { onClick: () => onGenerateEmbeddings("direct"), disabled: isGenerating, className: cn("flex items-center gap-2 rounded px-3 py-1.5 text-sm font-medium transition-colors", {
                                    "bg-feedback-red hover:bg-feedback-red cursor-pointer text-white": !isGenerating,
                                    "bg-neutral-grey-10 text-neutral-grey-50 cursor-not-allowed": isGenerating,
                                }), children: [_jsx(CheckCircle, { className: "h-4 w-4", strokeWidth: 1 }), isGenerating
                                        ? "Starting..."
                                        : `Direct (~$${directCost.toFixed(2)})`] }), _jsxs("button", { onClick: onClearStaging, disabled: isGenerating, className: cn("flex items-center gap-2 rounded px-3 py-1.5 text-sm font-medium transition-colors", {
                                    "bg-neutral-grey-50 hover:bg-neutral-grey-100 cursor-pointer text-white": !isGenerating,
                                    "bg-neutral-grey-10 text-neutral-grey-50 cursor-not-allowed": isGenerating,
                                }), children: [_jsx(DeleteIcon, { size: "lg" }), "Cancel"] })] })] }));
        }
        else if (completedCount > 0) {
            return (_jsxs("button", { onClick: onFinalize, disabled: isFinalizing, className: cn("flex items-center gap-2 rounded px-3 py-1.5 text-sm font-medium transition-colors", {
                    "bg-feedback-green hover:bg-feedback-green cursor-pointer text-white": !isFinalizing,
                    "bg-neutral-grey-10 text-neutral-grey-50 cursor-not-allowed": isFinalizing,
                }), children: [_jsx(CheckCircle, { className: "h-4 w-4", strokeWidth: 1 }), isFinalizing ? "Importing..." : "Import embeddings"] }));
        }
        const collectingNow = isCollecting || collectionStatus?.isCollecting;
        return (_jsxs("div", { className: "space-y-2", children: [_jsxs("label", { className: "text-neutral-grey-50 flex cursor-pointer items-center gap-2 text-sm", children: [_jsx("input", { type: "checkbox", checked: forceRegenerate, onChange: (e) => onForceRegenerateChange(e.target.checked), disabled: collectingNow, className: "border-border-default text-feedback-blue focus:ring-feedback-blue h-4 w-4 rounded" }), "Force regenerate all embeddings"] }), _jsxs("button", { onClick: onRebuild, disabled: collectingNow, className: cn("flex items-center gap-2 rounded px-3 py-1.5 text-sm font-medium transition-colors", {
                        "bg-feedback-blue hover:bg-feedback-blue cursor-pointer text-white": !collectingNow,
                        "bg-neutral-grey-10 text-neutral-grey-50 cursor-not-allowed": collectingNow,
                    }), children: [_jsx(RefreshCw, { className: "h-4 w-4", strokeWidth: 1 }), collectingNow ? "Collecting..." : "Rebuild Index"] })] }));
    })();
    // Next step info
    const nextStepInfo = !operationInProgress ? (hasPendingItems && !queueIsRunning ? (_jsxs("div", { className: "text-neutral-grey-100 text-xs", children: ["Next step:", " ", _jsxs("span", { className: "font-medium", children: ["Choose: ", providerInfo?.supportsBatchApi ? "Batch or " : "", "Direct generation"] })] })) : inProgressCount > 0 ? (_jsxs("div", { className: "text-neutral-grey-100 text-xs", children: ["Next step: ", _jsx("span", { className: "font-medium", children: "Generating Embeddings" })] })) : completedCount > 0 ? (_jsxs("div", { className: "text-neutral-grey-100 text-xs", children: ["Next step: ", _jsx("span", { className: "font-medium", children: "Import embeddings" })] })) : null) : null;
    return (_jsx(Card, { icon: _jsx(RefreshCw, { strokeWidth: 1, className: "h-5 w-5" }), title: "Rebuild index", description: "Collect content, generate embeddings, and finalize the search index.", children: _jsxs("div", { className: "space-y-2", children: [rebuildStatusDisplay, actionButtons, nextStepInfo && !hasPendingItems && (_jsx("div", { className: "text-neutral-grey-100 text-xs", children: nextStepInfo }))] }) }));
}
//# sourceMappingURL=RebuildIndexSection.js.map