/**
 * Enhanced Confirmation Dialog
 *
 * Improved confirmation dialog with:
 * - Side-by-side diff preview
 * - Syntax highlighted file preview
 * - File size change indication
 * - Timeout with auto-cancel
 * - Better visual feedback
 */
import React, { useState, useCallback, useEffect, useMemo } from "react";
import { Box, Text, useInput } from "ink";
import { DiffRenderer } from "./DiffRenderer.js";
/**
 * Confirmation options
 */
const CONFIRMATION_OPTIONS = [
    { key: "y", label: "Yes", description: "Proceed with this operation" },
    { key: "a", label: "Yes to all", description: "Don't ask again this session" },
    { key: "n", label: "No", description: "Cancel this operation" },
    { key: "f", label: "No + feedback", description: "Cancel and provide reason" },
];
/**
 * Operation type icons and colors
 */
const OPERATION_CONFIG = {
    create: { icon: "+", color: "green", label: "CREATE" },
    edit: { icon: "~", color: "yellow", label: "EDIT" },
    delete: { icon: "-", color: "red", label: "DELETE" },
    execute: { icon: "▶", color: "cyan", label: "EXECUTE" },
    move: { icon: "→", color: "blue", label: "MOVE" },
    rename: { icon: "↔", color: "magenta", label: "RENAME" },
    install: { icon: "⬇", color: "green", label: "INSTALL" },
    other: { icon: "•", color: "white", label: "OPERATION" },
};
/**
 * Format file size
 */
function formatSize(bytes) {
    if (bytes < 1024)
        return `${bytes} B`;
    if (bytes < 1024 * 1024)
        return `${(bytes / 1024).toFixed(1)} KB`;
    return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}
/**
 * Calculate size change indicator
 */
function SizeChange({ oldSize, newSize }) {
    if (oldSize === undefined || newSize === undefined)
        return null;
    const diff = newSize - oldSize;
    const percentage = oldSize > 0 ? ((diff / oldSize) * 100).toFixed(1) : "new";
    if (diff === 0) {
        return React.createElement(Text, { dimColor: true }, " (no size change)");
    }
    const color = diff > 0 ? "yellow" : "green";
    const sign = diff > 0 ? "+" : "";
    return (React.createElement(Text, { color: color },
        " ",
        "(",
        sign,
        formatSize(Math.abs(diff)),
        ", ",
        sign,
        percentage,
        "%)"));
}
/**
 * Enhanced Confirmation Dialog Component
 */
export function EnhancedConfirmationDialog({ operation, operationType = "other", filename, onConfirm, onReject, showVSCodeOpen = false, content, originalContent: _originalContent, newContent: _newContent, timeout, showFileInfo = true, fileSize, newFileSize, }) {
    const [selectedOption, setSelectedOption] = useState(0);
    const [feedbackMode, setFeedbackMode] = useState(false);
    const [feedback, setFeedback] = useState("");
    const [remainingTime, setRemainingTime] = useState(timeout);
    const [showFullDiff, setShowFullDiff] = useState(false);
    const config = OPERATION_CONFIG[operationType];
    // Countdown timer
    useEffect(() => {
        if (!timeout || remainingTime === undefined || remainingTime <= 0)
            return;
        const timer = setInterval(() => {
            setRemainingTime((prev) => {
                if (prev === undefined || prev <= 1) {
                    onReject("Operation cancelled: timeout");
                    return 0;
                }
                return prev - 1;
            });
        }, 1000);
        return () => clearInterval(timer);
    }, [timeout, remainingTime, onReject]);
    // Handle keyboard input
    const handleInput = useCallback((input, key) => {
        if (feedbackMode) {
            if (key.return) {
                onReject(feedback.trim() || "User provided no feedback");
                return;
            }
            if (key.escape) {
                setFeedbackMode(false);
                setFeedback("");
                return;
            }
            if (key.backspace || key.delete) {
                setFeedback((prev) => prev.slice(0, -1));
                return;
            }
            if (input && !key.ctrl && !key.meta) {
                setFeedback((prev) => prev + input);
            }
            return;
        }
        // Quick key shortcuts
        if (input === "y" || input === "Y") {
            onConfirm(false);
            return;
        }
        if (input === "a" || input === "A") {
            onConfirm(true);
            return;
        }
        if (input === "n" || input === "N") {
            onReject("Operation cancelled by user");
            return;
        }
        if (input === "f" || input === "F") {
            setFeedbackMode(true);
            return;
        }
        // Toggle full diff view
        if (input === "d" || input === "D") {
            setShowFullDiff((prev) => !prev);
            return;
        }
        // Arrow navigation
        if (key.upArrow || (key.shift && key.tab)) {
            setSelectedOption((prev) => prev > 0 ? prev - 1 : CONFIRMATION_OPTIONS.length - 1);
            return;
        }
        if (key.downArrow || key.tab) {
            setSelectedOption((prev) => (prev + 1) % CONFIRMATION_OPTIONS.length);
            return;
        }
        if (key.return) {
            switch (selectedOption) {
                case 0:
                    onConfirm(false);
                    break;
                case 1:
                    onConfirm(true);
                    break;
                case 2:
                    onReject("Operation cancelled by user");
                    break;
                case 3:
                    setFeedbackMode(true);
                    break;
            }
            return;
        }
        if (key.escape) {
            onReject("Operation cancelled by user (Escape)");
        }
    }, [feedbackMode, feedback, selectedOption, onConfirm, onReject]);
    useInput(handleInput);
    // Calculate diff stats if content provided
    const diffStats = useMemo(() => {
        if (!content)
            return null;
        const lines = content.split("\n");
        const additions = lines.filter((l) => l.startsWith("+") && !l.startsWith("+++")).length;
        const deletions = lines.filter((l) => l.startsWith("-") && !l.startsWith("---")).length;
        return { additions, deletions, total: lines.length };
    }, [content]);
    // Feedback mode UI
    if (feedbackMode) {
        return (React.createElement(Box, { flexDirection: "column", padding: 1 },
            React.createElement(Box, { marginBottom: 1 },
                React.createElement(Text, { color: "yellow" }, "Provide feedback for cancellation:")),
            React.createElement(Box, { borderStyle: "round", borderColor: "yellow", paddingX: 1 },
                React.createElement(Text, { color: "gray" }, "\u276F "),
                React.createElement(Text, null,
                    feedback,
                    React.createElement(Text, { backgroundColor: "white", color: "black" }, " "))),
            React.createElement(Box, { marginTop: 1 },
                React.createElement(Text, { dimColor: true }, "Enter to submit \u2022 Esc to go back"))));
    }
    return (React.createElement(Box, { flexDirection: "column" },
        React.createElement(Box, { marginTop: 1 },
            React.createElement(Text, { color: config.color, bold: true },
                "[",
                config.label,
                "]"),
            React.createElement(Text, null, " "),
            React.createElement(Text, { color: config.color }, config.icon),
            React.createElement(Text, { color: "white" },
                " ",
                operation)),
        React.createElement(Box, { marginLeft: 2, flexDirection: "column" },
            React.createElement(Box, null,
                React.createElement(Text, { color: "cyan" }, "File: "),
                React.createElement(Text, { bold: true }, filename),
                showFileInfo && fileSize !== undefined && (React.createElement(React.Fragment, null,
                    React.createElement(Text, { dimColor: true },
                        " (",
                        formatSize(fileSize),
                        ")"),
                    React.createElement(SizeChange, { oldSize: fileSize, newSize: newFileSize })))),
            showVSCodeOpen && (React.createElement(Box, { marginTop: 1 },
                React.createElement(Text, { color: "gray" }, "\u23BF Opened in Visual Studio Code \u29C9"))),
            diffStats && (React.createElement(Box, { marginTop: 1 },
                React.createElement(Text, { dimColor: true }, "Changes: "),
                React.createElement(Text, { color: "green" },
                    "+",
                    diffStats.additions),
                React.createElement(Text, { dimColor: true }, " / "),
                React.createElement(Text, { color: "red" },
                    "-",
                    diffStats.deletions),
                React.createElement(Text, { dimColor: true }, " lines"),
                content && content.split("\n").length > 15 && (React.createElement(Text, { dimColor: true },
                    " (press 'd' to ",
                    showFullDiff ? "collapse" : "expand",
                    ")")))),
            content && (React.createElement(Box, { marginTop: 1, flexDirection: "column" },
                React.createElement(Text, { dimColor: true }, "Preview:"),
                React.createElement(Box, { marginLeft: 2, flexDirection: "column", borderStyle: "single", borderColor: "gray", paddingX: 1 },
                    React.createElement(DiffRenderer, { diffContent: showFullDiff ? content : content.split("\n").slice(0, 10).join("\n"), filename: filename, terminalWidth: 76 }),
                    !showFullDiff && content.split("\n").length > 10 && (React.createElement(Text, { dimColor: true },
                        "... ",
                        content.split("\n").length - 10,
                        " more lines")))))),
        timeout && remainingTime !== undefined && remainingTime > 0 && (React.createElement(Box, { marginTop: 1, marginLeft: 2 },
            React.createElement(Text, { color: remainingTime <= 10 ? "red" : "yellow" },
                "\u23F1 Auto-cancel in ",
                remainingTime,
                "s"))),
        React.createElement(Box, { marginTop: 1 },
            React.createElement(Text, { bold: true }, "Proceed with this operation?")),
        React.createElement(Box, { flexDirection: "column", marginTop: 1 }, CONFIRMATION_OPTIONS.map((option, index) => (React.createElement(Box, { key: option.key, paddingLeft: 1 },
            React.createElement(Text, { color: selectedOption === index ? "black" : "white", backgroundColor: selectedOption === index ? "cyan" : undefined },
                "[",
                option.key,
                "] ",
                option.label),
            selectedOption === index && (React.createElement(Text, { dimColor: true },
                " - ",
                option.description)))))),
        React.createElement(Box, { marginTop: 1 },
            React.createElement(Text, { dimColor: true }, "\u2191\u2193 navigate \u2022 Enter select \u2022 y/n quick keys \u2022 d toggle diff \u2022 Esc cancel"))));
}
export default EnhancedConfirmationDialog;
//# sourceMappingURL=EnhancedConfirmationDialog.js.map