import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
/**
 * @license
 * Copyright 2025 Vybestack LLC
 * SPDX-License-Identifier: Apache-2.0
 */
import React, { useState, useMemo } from 'react';
import { Box, Text } from 'ink';
import { SemanticColors } from '../colors.js';
import { useResponsive } from '../hooks/useResponsive.js';
import { truncateEnd } from '../utils/responsive.js';
import { useKeypress } from '../hooks/useKeypress.js';
export const ProfileListDialog = ({ profiles, onSelect, onClose, onViewDetail, isLoading = false, defaultProfileName, activeProfileName, }) => {
    const { isNarrow, isWide, width } = useResponsive();
    const [searchTerm, setSearchTerm] = useState('');
    const [isSearching, setIsSearching] = useState(true); // Start in search mode
    const [index, setIndex] = useState(0);
    // Filter profiles based on search term
    const filteredProfiles = useMemo(() => profiles.filter((p) => p.name.toLowerCase().includes(searchTerm.toLowerCase())), [profiles, searchTerm]);
    // Reset index when search term changes
    React.useEffect(() => {
        setIndex(0);
    }, [searchTerm]);
    // Clamp index when the underlying list changes.
    React.useEffect(() => {
        setIndex((prev) => {
            if (filteredProfiles.length === 0)
                return 0;
            return Math.min(prev, filteredProfiles.length - 1);
        });
    }, [filteredProfiles.length]);
    const columns = isNarrow ? 1 : isWide ? 3 : 2;
    const longest = filteredProfiles.reduce((len, p) => Math.max(len, p.name.length + 10), // account for indicators
    0);
    const colWidth = isWide
        ? Math.max(longest + 4, 35)
        : Math.max(longest + 4, 25);
    const rows = Math.ceil(filteredProfiles.length / columns);
    const move = (delta) => {
        if (filteredProfiles.length === 0) {
            setIndex(0);
            return;
        }
        let next = index + delta;
        if (next < 0)
            next = 0;
        if (next >= filteredProfiles.length)
            next = filteredProfiles.length - 1;
        setIndex(next);
    };
    useKeypress((key) => {
        if (key.name === 'escape') {
            if (isSearching && searchTerm.length > 0) {
                setSearchTerm('');
            }
            else {
                return onClose();
            }
        }
        if (isSearching || isNarrow) {
            if (key.name === 'return') {
                if (filteredProfiles.length > 0) {
                    if (isNarrow) {
                        return onViewDetail(filteredProfiles[index].name);
                    }
                    setIsSearching(false);
                }
            }
            else if (key.name === 'tab' && !isNarrow) {
                setIsSearching(false);
            }
            else if (key.name === 'backspace' || key.name === 'delete') {
                setSearchTerm((prev) => prev.slice(0, -1));
            }
            else if (key.sequence &&
                typeof key.sequence === 'string' &&
                !key.ctrl &&
                !key.meta &&
                key.sequence.length === 1) {
                setSearchTerm((prev) => prev + key.sequence);
            }
        }
        else {
            // Navigation mode
            if (key.name === 'return' && filteredProfiles.length > 0) {
                return onViewDetail(filteredProfiles[index].name);
            }
            if (key.name === 'tab') {
                setIsSearching(true);
            }
            if (filteredProfiles.length === 0) {
                return;
            }
            // Quick actions
            if (key.sequence === 'l' && filteredProfiles.length > 0) {
                return onSelect(filteredProfiles[index].name);
            }
            // Navigation
            if (key.name === 'left')
                move(-1);
            if (key.name === 'right')
                move(1);
            if (key.name === 'up')
                move(-columns);
            if (key.name === 'down')
                move(columns);
            // Vim-style navigation
            if (key.sequence === 'j')
                move(columns);
            if (key.sequence === 'k')
                move(-columns);
            if (key.sequence === 'h')
                move(-1);
        }
    }, { isActive: !isLoading });
    const renderItem = (profile, i) => {
        const selected = i === index && (!isSearching || isNarrow);
        const isActiveProfile = profile.name === activeProfileName;
        const isDefaultProfile = profile.name === defaultProfileName;
        // Build indicators
        let indicators = '';
        if (isActiveProfile)
            indicators += '*';
        if (isDefaultProfile)
            indicators += 'D';
        if (profile.type === 'loadbalancer')
            indicators += 'LB';
        const indicatorText = indicators ? ` [${indicators}]` : '';
        // Truncate name if needed
        const maxNameLen = colWidth - 6 - indicatorText.length;
        const displayName = isWide
            ? profile.name
            : profile.name.length > maxNameLen
                ? truncateEnd(profile.name, maxNameLen)
                : profile.name;
        return (_jsx(Box, { width: isWide ? undefined : colWidth, marginRight: 2, children: _jsxs(Text, { color: selected
                    ? SemanticColors.text.accent
                    : isSearching && !isNarrow
                        ? SemanticColors.text.secondary
                        : isActiveProfile
                            ? SemanticColors.status.success
                            : SemanticColors.text.primary, children: [selected ? '● ' : '○ ', displayName, indicatorText && (_jsx(Text, { color: SemanticColors.text.secondary, children: indicatorText }))] }) }, profile.name));
    };
    const grid = [];
    for (let r = 0; r < rows; r++) {
        const rowItems = [];
        for (let c = 0; c < columns; c++) {
            const i = r * columns + c;
            if (i < filteredProfiles.length) {
                rowItems.push(renderItem(filteredProfiles[i], i));
            }
        }
        grid.push(_jsx(Box, { children: rowItems }, r));
    }
    if (isLoading) {
        return (_jsx(Box, { borderStyle: "round", borderColor: SemanticColors.border.default, flexDirection: "column", padding: 1, children: _jsx(Text, { color: SemanticColors.text.primary, children: "Loading profiles..." }) }));
    }
    if (profiles.length === 0) {
        return (_jsxs(Box, { borderStyle: "round", borderColor: SemanticColors.border.default, flexDirection: "column", padding: 1, children: [_jsx(Text, { color: SemanticColors.text.primary, children: "No saved profiles found. Use /profile save model <name> to create one." }), _jsx(Text, { color: SemanticColors.text.secondary, children: "Press Esc to close" })] }));
    }
    const renderContent = () => {
        if (isNarrow) {
            return (_jsxs(Box, { flexDirection: "column", children: [_jsx(Text, { bold: true, color: SemanticColors.text.primary, children: "Profiles" }), _jsxs(Box, { marginY: 1, children: [_jsxs(Text, { color: SemanticColors.text.primary, children: ["Search: ", _jsx(Text, { color: SemanticColors.text.accent, children: "\u258C" })] }), _jsx(Text, { color: SemanticColors.text.primary, children: searchTerm })] }), _jsx(Text, { color: SemanticColors.text.secondary, children: "Type to filter, Enter for details, Esc to cancel" }), _jsxs(Text, { color: SemanticColors.text.secondary, children: [filteredProfiles.length, " profiles", searchTerm && ' found'] }), filteredProfiles.length > 0 ? (grid) : (_jsx(Box, { marginY: 1, children: _jsxs(Text, { color: SemanticColors.text.secondary, children: ["No profiles match \"", searchTerm, "\""] }) }))] }));
        }
        return (_jsxs(Box, { flexDirection: "column", children: [_jsx(Text, { bold: true, color: SemanticColors.text.primary, children: "Profile List" }), _jsxs(Box, { marginY: 1, children: [_jsxs(Text, { color: isSearching
                                ? SemanticColors.text.primary
                                : SemanticColors.text.secondary, children: ["Search:", ' ', isSearching && _jsx(Text, { color: SemanticColors.text.accent, children: "\u258C" })] }), _jsx(Text, { color: SemanticColors.text.primary, children: searchTerm }), _jsxs(Text, { color: SemanticColors.text.secondary, children: [' ', "(press Tab to ", isSearching ? 'navigate' : 'search', ") Found", ' ', filteredProfiles.length, " profiles"] })] }), filteredProfiles.length > 0 ? (grid) : (_jsx(Box, { marginY: 1, children: _jsxs(Text, { color: SemanticColors.text.secondary, children: ["No profiles match \"", searchTerm, "\""] }) })), filteredProfiles.length > 0 && !isSearching && (_jsx(Box, { marginTop: 1, children: _jsxs(Text, { color: SemanticColors.text.secondary, children: ["Selected: ", filteredProfiles[index].name, filteredProfiles[index].provider && (_jsxs(Text, { color: SemanticColors.text.secondary, children: [' ', "(", filteredProfiles[index].provider, filteredProfiles[index].model &&
                                        ` / ${filteredProfiles[index].model}`, ")"] }))] }) })), _jsx(Box, { marginTop: 1, children: _jsx(Text, { color: SemanticColors.text.secondary, children: "Legend: * = active, D = default, LB = load balancer" }) }), _jsx(Box, { marginTop: 1 }), _jsx(Text, { color: SemanticColors.text.secondary, children: "Controls: \u2191\u2193\u2190\u2192 Navigate [Enter] Details [l] Load [Esc] Close" })] }));
    };
    return isNarrow ? (_jsx(Box, { flexDirection: "column", padding: 1, children: renderContent() })) : (_jsx(Box, { borderStyle: "round", borderColor: SemanticColors.border.default, flexDirection: "column", padding: 1, width: Math.min(width, 100), children: renderContent() }));
};
//# sourceMappingURL=ProfileListDialog.js.map