import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { RefreshCw, CheckCircle, Trash2 } from "lucide-react";
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: "rounded bg-gray-50 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: "ml-auto shrink-0 rounded bg-gray-700 px-3 py-1.5 text-sm font-medium text-white hover:bg-gray-800", 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
                                ? "cursor-not-allowed bg-gray-300 text-gray-500"
                                : "bg-gray-700 text-white hover:bg-gray-800"), children: isCancellingCollection ? "Cancelling..." : "Cancel" }))] }), rebuildStatus.progressDetails &&
                    rebuildStatus.progressDetails.length > 0 && (_jsx("div", { className: "text-xs text-gray-600", children: rebuildStatus.progressDetails.join(" • ") })), !operationInProgress &&
                    rebuildStatus.errorCount !== undefined &&
                    rebuildStatus.errorCount > 0 && (_jsxs("div", { className: "text-xs text-orange-600", 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: "rounded bg-gray-50 p-3", children: [_jsxs("div", { className: "flex items-center justify-between text-sm text-gray-600", children: [_jsx("span", { children: "Pending Requests" }), _jsx("span", { children: pendingCount.toLocaleString() })] }), _jsxs("div", { className: "mt-1 flex items-center justify-between text-sm text-gray-600", children: [_jsx("span", { children: "Estimated Input Tokens" }), _jsx("span", { children: estimatedTokens.toLocaleString() })] }), supportsBatch && (_jsxs("div", { className: "mt-1 flex items-center justify-between text-sm text-gray-600", children: [_jsx("span", { children: "Estimated Batch Cost" }), _jsxs("span", { children: ["~$", batchCost.toFixed(2)] })] })), _jsxs("div", { className: "mt-1 flex items-center justify-between text-sm text-gray-600", 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", {
                                    "cursor-pointer bg-amber-600 text-white hover:bg-amber-700": !isGenerating,
                                    "cursor-not-allowed bg-gray-300 text-gray-500": 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", {
                                    "cursor-pointer bg-rose-600 text-white hover:bg-rose-700": !isGenerating,
                                    "cursor-not-allowed bg-gray-300 text-gray-500": 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", {
                                    "cursor-pointer bg-gray-600 text-white hover:bg-gray-700": !isGenerating,
                                    "cursor-not-allowed bg-gray-300 text-gray-500": isGenerating,
                                }), children: [_jsx(Trash2, { className: "h-4 w-4", strokeWidth: 1 }), "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", {
                    "cursor-pointer bg-green-600 text-white hover:bg-green-700": !isFinalizing,
                    "cursor-not-allowed bg-gray-300 text-gray-500": 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: "flex cursor-pointer items-center gap-2 text-sm text-gray-600", children: [_jsx("input", { type: "checkbox", checked: forceRegenerate, onChange: (e) => onForceRegenerateChange(e.target.checked), disabled: collectingNow, className: "h-4 w-4 rounded border-gray-300 text-indigo-600 focus:ring-indigo-500" }), "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", {
                        "cursor-pointer bg-indigo-600 text-white hover:bg-indigo-700": !collectingNow,
                        "cursor-not-allowed bg-gray-300 text-gray-500": 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-xs text-gray-700", children: ["Next step:", " ", _jsxs("span", { className: "font-medium", children: ["Choose: ", providerInfo?.supportsBatchApi ? "Batch or " : "", "Direct generation"] })] })) : inProgressCount > 0 ? (_jsxs("div", { className: "text-xs text-gray-700", children: ["Next step: ", _jsx("span", { className: "font-medium", children: "Generating Embeddings" })] })) : completedCount > 0 ? (_jsxs("div", { className: "text-xs text-gray-700", children: ["Next step: ", _jsx("span", { className: "font-medium", children: "Import embeddings" })] })) : null) : null;
    return (_jsxs("div", { className: "rounded-lg border border-gray-200 bg-white p-3", children: [_jsx("h3", { className: "mb-2 text-xs font-semibold text-gray-700", children: "Rebuild Index" }), _jsxs("div", { className: "space-y-2", children: [rebuildStatusDisplay, actionButtons, nextStepInfo && !hasPendingItems && (_jsx("div", { className: "text-xs text-gray-700", children: nextStepInfo }))] })] }));
}
//# sourceMappingURL=RebuildIndexSection.js.map