"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AgentProfiles = void 0;
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = require("react");
const useWebSocket_js_1 = require("../../hooks/useWebSocket.js");
const useKeyboardShortcuts_js_1 = require("../../hooks/useKeyboardShortcuts.js");
const useLocalStorage_js_1 = require("../../hooks/useLocalStorage.js");
const useDragAndDrop_js_1 = require("../../hooks/useDragAndDrop.js");
const AgentCard_js_1 = require("./AgentCard.js");
const AgentListView_js_1 = require("./AgentListView.js");
const AgentTableView_js_1 = require("./AgentTableView.js");
const AgentCreationWizard_js_1 = require("./AgentCreationWizard.js");
const AgentTestingPlayground_js_1 = require("./AgentTestingPlayground.js");
const AgentHealthMonitor_js_1 = require("./AgentHealthMonitor.js");
const AgentMetricsPanel_js_1 = require("./AgentMetricsPanel.js");
const AgentFiltersPanel_js_1 = require("./AgentFiltersPanel.js");
const BulkOperationsToolbar_js_1 = require("./BulkOperationsToolbar.js");
const LayoutEditor_js_1 = require("./LayoutEditor.js");
const ConversationInsights_js_1 = require("./ConversationInsights.js");
const Alert_js_1 = require("../feedback/Alert.js");
const Modal_js_1 = require("../feedback/Modal.js");
const Loader_js_1 = require("../feedback/Loader.js");
const Button_js_1 = require("../Button.js");
const SearchInput_js_1 = require("../Form/SearchInput.js");
/**
 * AgentProfiles - Comprehensive AI Agent Management System
 *
 * Advanced features:
 * - Real-time updates via WebSocket
 * - Multiple view modes (cards, list, table)
 * - Drag-and-drop layout customization
 * - Bulk operations
 * - Advanced filtering and semantic search
 * - Live agent testing playground
 * - Health monitoring with predictive analytics
 * - Import/export capabilities
 * - Keyboard shortcuts and accessibility
 * - Performance metrics and insights
 */
const AgentProfiles = ({ className = '', showMetrics = true, autoRefresh = true, realTimeUpdates = true, enableBulkOperations = true, enableAdvancedFiltering = true, enableSemanticSearch = true, enableSavedFilters = true, showLiveMetrics = true, showConversationInsights = true, showHealthMonitoring = true, enableAgentTesting = true, enableConfigValidation = true, enableImportExport = true, enableCustomLayout = true, enableKeyboardShortcuts = true, enableMultipleViews = true, refreshInterval = 30000, // 30 seconds
maxAgentsPerPage = 20, onAgentSelect, onAgentCreate, onAgentUpdate, onAgentDelete }) => {
    // Core state management
    const { agents, loading, error, filters, selectedAgents, metrics, fetchAgents, createAgent, updateAgent, deleteAgent, bulkPauseAgents, bulkResumeAgents, bulkDeleteAgents, setFilters, setSelectedAgents, clearError } = {
        agents: [],
        loading: true,
        error: null,
        filters: {
            status: [],
            type: [],
            model: [],
            health_range: [],
        },
        selectedAgents: [],
        metrics: [],
        fetchAgents: () => { },
        createAgent: (agent) => { },
        updateAgent: (agent) => { },
        deleteAgent: (id) => { },
        bulkPauseAgents: (ids) => { },
        bulkResumeAgents: (ids) => { },
        bulkDeleteAgents: (ids) => { },
        setFilters: (filters) => { },
        setSelectedAgents: (ids) => { },
        clearError: () => { }
    };
    // Local state for UI interactions
    const [viewMode, setViewMode] = (0, useLocalStorage_js_1.useLocalStorage)('agentProfiles.viewMode', 'cards');
    const [layoutMode, setLayoutMode] = (0, useLocalStorage_js_1.useLocalStorage)('agentProfiles.layoutMode', 'default');
    const [searchTerm, setSearchTerm] = (0, react_1.useState)('');
    const [showWizard, setShowWizard] = (0, react_1.useState)(false);
    const [showTesting, setShowTesting] = (0, react_1.useState)(false);
    const [showHealth, setShowHealth] = (0, react_1.useState)(false);
    const [showInsights, setShowInsights] = (0, react_1.useState)(false);
    const [showLayoutEditor, setShowLayoutEditor] = (0, react_1.useState)(false);
    const [selectedAgent, setSelectedAgent] = (0, react_1.useState)(null);
    const [currentPage, setCurrentPage] = (0, react_1.useState)(1);
    const [sortBy, setSortBy] = (0, react_1.useState)('last_active');
    const [sortOrder, setSortOrder] = (0, react_1.useState)('desc');
    // Refs for advanced features
    const searchInputRef = (0, react_1.useRef)(null);
    const dragContainerRef = (0, react_1.useRef)(null);
    // WebSocket for real-time updates
    const { isConnected, lastMessage } = (0, useWebSocket_js_1.useWebSocket)(realTimeUpdates ? 'ws://localhost:3000/agent-updates' : null, {
        onMessage: (message) => {
            const data = JSON.parse(message.data);
            if (data.type === 'agent_update') {
                // Handle real-time agent updates
                fetchAgents();
            }
        }
    });
    // Keyboard shortcuts
    (0, useKeyboardShortcuts_js_1.useKeyboardShortcuts)(enableKeyboardShortcuts ? {
        'ctrl+n': () => setShowWizard(true),
        'ctrl+f': () => searchInputRef.current?.focus(),
        'ctrl+a': () => setSelectedAgents(agents.map(a => a.id)),
        'escape': () => {
            setShowWizard(false);
            setShowTesting(false);
            setShowHealth(false);
            setShowInsights(false);
            setSelectedAgents([]);
        }
    } : {});
    // Drag and drop for custom layouts
    const { dragHandlers, dropTarget } = (0, useDragAndDrop_js_1.useDragAndDrop)({
        enabled: enableCustomLayout && showLayoutEditor,
        onDrop: (item, target) => {
            // Handle layout changes
            console.log('Layout changed:', item, target);
        }
    });
    // Auto-refresh functionality
    (0, react_1.useEffect)(() => {
        if (autoRefresh) {
            const interval = setInterval(fetchAgents, refreshInterval);
            return () => clearInterval(interval);
        }
    }, [autoRefresh, refreshInterval, fetchAgents]);
    // Filter and search logic
    const filteredAgents = (0, react_1.useMemo)(() => {
        let filtered = agents;
        // Apply search filter (semantic search if enabled)
        if (searchTerm) {
            if (enableSemanticSearch) {
                // TODO: Implement semantic search with AI embeddings
                filtered = filtered.filter(agent => agent.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
                    agent.description?.toLowerCase().includes(searchTerm.toLowerCase()) ||
                    agent.capabilities.some(cap => cap.toLowerCase().includes(searchTerm.toLowerCase())) ||
                    agent.tools.some(tool => tool.toLowerCase().includes(searchTerm.toLowerCase())));
            }
            else {
                filtered = filtered.filter(agent => agent.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
                    agent.description?.toLowerCase().includes(searchTerm.toLowerCase()));
            }
        }
        // Apply filters
        if (filters.status && filters.status.length > 0) {
            filtered = filtered.filter(agent => filters.status.includes(agent.status));
        }
        if (filters.type && filters.type.length > 0) {
            filtered = filtered.filter(agent => filters.type.includes(agent.type));
        }
        if (filters.model && filters.model.length > 0) {
            filtered = filtered.filter(agent => filters.model.includes(agent.model));
        }
        if (filters.health_range) {
            filtered = filtered.filter(agent => agent.health >= filters.health_range[0] &&
                agent.health <= filters.health_range[1]);
        }
        // Apply sorting
        filtered.sort((a, b) => {
            let comparison = 0;
            switch (sortBy) {
                case 'name':
                    comparison = a.name.localeCompare(b.name);
                    break;
                case 'health':
                    comparison = a.health - b.health;
                    break;
                case 'conversations':
                    comparison = a.conversations - b.conversations;
                    break;
                case 'success_rate':
                    comparison = a.success_rate - b.success_rate;
                    break;
                case 'last_active':
                    comparison = new Date(a.last_active).getTime() - new Date(b.last_active).getTime();
                    break;
                default:
                    comparison = 0;
            }
            return sortOrder === 'desc' ? -comparison : comparison;
        });
        return filtered;
    }, [agents, searchTerm, filters, sortBy, sortOrder, enableSemanticSearch]);
    // Pagination
    const paginatedAgents = (0, react_1.useMemo)(() => {
        const startIndex = (currentPage - 1) * maxAgentsPerPage;
        return filteredAgents.slice(startIndex, startIndex + maxAgentsPerPage);
    }, [filteredAgents, currentPage, maxAgentsPerPage]);
    const totalPages = Math.ceil(filteredAgents.length / maxAgentsPerPage);
    // Event handlers
    const handleAgentSelect = (0, react_1.useCallback)((agent) => {
        setSelectedAgent(agent);
        onAgentSelect?.(agent);
    }, [onAgentSelect]);
    const handleBulkOperation = (0, react_1.useCallback)(async (operation) => {
        try {
            switch (operation) {
                case 'pause':
                    await bulkPauseAgents(selectedAgents);
                    break;
                case 'resume':
                    await bulkResumeAgents(selectedAgents);
                    break;
                case 'delete':
                    if (window.confirm(`Delete ${selectedAgents.length} agents?`)) {
                        await bulkDeleteAgents(selectedAgents);
                    }
                    break;
            }
            setSelectedAgents([]);
        }
        catch (error) {
            console.error('Bulk operation failed:', error);
        }
    }, [selectedAgents, bulkPauseAgents, bulkResumeAgents, bulkDeleteAgents, setSelectedAgents]);
    const handleViewModeChange = (0, react_1.useCallback)((mode) => {
        setViewMode(mode);
        setCurrentPage(1);
    }, [setViewMode]);
    // Render functions
    const renderAgentView = () => {
        const commonProps = {
            agents: paginatedAgents,
            selectedAgents,
            onAgentSelect: handleAgentSelect,
            onSelectChange: setSelectedAgents,
            enableBulkOperations,
            sortBy,
            sortOrder,
            onSortChange: (field) => {
                if (field === sortBy) {
                    setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc');
                }
                else {
                    setSortBy(field);
                    setSortOrder('desc');
                }
            }
        };
        switch (viewMode) {
            case 'list':
                return ((0, jsx_runtime_1.jsx)("div", { "data-testid": "agents-list-view", children: (0, jsx_runtime_1.jsx)(AgentListView_js_1.AgentListView, { ...commonProps }) }));
            case 'table':
                return ((0, jsx_runtime_1.jsx)("div", { "data-testid": "agents-table-view", children: (0, jsx_runtime_1.jsx)(AgentTableView_js_1.AgentTableView, { ...commonProps }) }));
            case 'cards':
            default:
                return ((0, jsx_runtime_1.jsx)("div", { "data-testid": "agents-card-view", children: (0, jsx_runtime_1.jsx)("div", { className: "grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6", children: paginatedAgents.map((agent) => ((0, jsx_runtime_1.jsx)(AgentCard_js_1.AgentCard, { agent: agent, selected: selectedAgents.includes(agent.id), onSelect: () => handleAgentSelect(agent), onToggleSelect: (selected) => {
                                if (selected) {
                                    setSelectedAgents([...selectedAgents, agent.id]);
                                }
                                else {
                                    setSelectedAgents(selectedAgents.filter(id => id !== agent.id));
                                }
                            }, enableBulkOperations: enableBulkOperations, showLiveMetrics: showLiveMetrics }, agent.id))) }) }));
        }
    };
    // Render loading state
    if (loading && agents.length === 0) {
        return ((0, jsx_runtime_1.jsxs)("div", { className: "flex items-center justify-center h-64", children: [(0, jsx_runtime_1.jsx)(Loader_js_1.Loader, { size: "large" }), (0, jsx_runtime_1.jsx)("span", { className: "ml-4 text-gray-600", children: "Loading agents..." })] }));
    }
    // Render error state
    if (error && agents.length === 0) {
        return ((0, jsx_runtime_1.jsx)(Alert_js_1.Alert, { type: "error", title: "Failed to load agents", message: error, actions: [
                {
                    label: 'Retry',
                    onClick: () => {
                        clearError();
                        fetchAgents();
                    },
                    variant: 'primary'
                }
            ] }));
    }
    return ((0, jsx_runtime_1.jsxs)("div", { className: `agent-profiles ${className}`, "data-testid": "agent-profiles-dashboard", role: "main", "aria-label": "Agent Profiles Dashboard", children: [(0, jsx_runtime_1.jsx)("div", { className: "mb-6", "data-testid": "agent-profiles-header", children: (0, jsx_runtime_1.jsxs)("div", { className: "flex items-center justify-between", children: [(0, jsx_runtime_1.jsxs)("div", { children: [(0, jsx_runtime_1.jsx)("h1", { className: "text-2xl font-bold text-gray-900", children: "Agent Profiles" }), (0, jsx_runtime_1.jsxs)("p", { className: "text-gray-600", children: [filteredAgents.length, " of ", agents.length, " agents", realTimeUpdates && ((0, jsx_runtime_1.jsx)("span", { className: `ml-2 inline-flex items-center px-2 py-1 rounded-full text-xs ${isConnected ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'}`, children: isConnected ? '● Live' : '● Offline' }))] })] }), (0, jsx_runtime_1.jsxs)("div", { className: "flex items-center space-x-3", children: [enableMultipleViews && ((0, jsx_runtime_1.jsxs)("div", { className: "flex items-center space-x-1 bg-gray-100 rounded-lg p-1", children: [(0, jsx_runtime_1.jsx)("button", { onClick: () => handleViewModeChange('cards'), className: `p-2 rounded ${viewMode === 'cards' ? 'bg-white shadow' : 'hover:bg-gray-200'}`, "data-testid": "view-mode-cards", "aria-label": "Card view", children: (0, jsx_runtime_1.jsx)("svg", { className: "w-4 h-4", fill: "currentColor", viewBox: "0 0 20 20", children: (0, jsx_runtime_1.jsx)("path", { d: "M5 3a2 2 0 00-2 2v2a2 2 0 002 2h2a2 2 0 002-2V5a2 2 0 00-2-2H5zM5 11a2 2 0 00-2 2v2a2 2 0 002 2h2a2 2 0 002-2v-2a2 2 0 00-2-2H5zM11 5a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2V5zM11 13a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2v-2z" }) }) }), (0, jsx_runtime_1.jsx)("button", { onClick: () => handleViewModeChange('list'), className: `p-2 rounded ${viewMode === 'list' ? 'bg-white shadow' : 'hover:bg-gray-200'}`, "data-testid": "view-mode-list", "aria-label": "List view", children: (0, jsx_runtime_1.jsx)("svg", { className: "w-4 h-4", fill: "currentColor", viewBox: "0 0 20 20", children: (0, jsx_runtime_1.jsx)("path", { fillRule: "evenodd", d: "M3 4a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zm0 4a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zm0 4a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1z", clipRule: "evenodd" }) }) }), (0, jsx_runtime_1.jsx)("button", { onClick: () => handleViewModeChange('table'), className: `p-2 rounded ${viewMode === 'table' ? 'bg-white shadow' : 'hover:bg-gray-200'}`, "data-testid": "view-mode-table", "aria-label": "Table view", children: (0, jsx_runtime_1.jsx)("svg", { className: "w-4 h-4", fill: "currentColor", viewBox: "0 0 20 20", children: (0, jsx_runtime_1.jsx)("path", { fillRule: "evenodd", d: "M5 4a1 1 0 00-1 1v10a1 1 0 001 1h10a1 1 0 001-1V5a1 1 0 00-1-1H5zm0 2h10v2H5V6zm0 4h4v2H5v-2zm6 0h4v2h-4v-2zm-6 4h4v2H5v-2zm6 0h4v2h-4v-2z", clipRule: "evenodd" }) }) })] })), enableCustomLayout && ((0, jsx_runtime_1.jsx)(Button_js_1.Button, { variant: "outline", onClick: () => setShowLayoutEditor(true), "aria-label": "Customize Layout", children: "Customize Layout" })), (0, jsx_runtime_1.jsx)(Button_js_1.Button, { onClick: () => setShowWizard(true), className: "bg-blue-600 hover:bg-blue-700", children: "Create Agent" })] })] }) }), error && ((0, jsx_runtime_1.jsx)("div", { className: "mb-4", children: (0, jsx_runtime_1.jsx)(Alert_js_1.Alert, { type: "error", title: "Error", message: error, onDismiss: clearError }) })), (0, jsx_runtime_1.jsxs)("div", { className: "flex gap-6", children: [(0, jsx_runtime_1.jsxs)("div", { className: "w-80 flex-shrink-0", "data-testid": "agent-profiles-sidebar", children: [showMetrics && ((0, jsx_runtime_1.jsx)("div", { className: "mb-6", "data-testid": "agent-metrics-panel", children: (0, jsx_runtime_1.jsx)(AgentMetricsPanel_js_1.AgentMetricsPanel, { metrics: metrics, showLiveMetrics: showLiveMetrics, autoRefresh: autoRefresh }) })), (0, jsx_runtime_1.jsx)("div", { "data-testid": "agent-profiles-filters", children: (0, jsx_runtime_1.jsx)(AgentFiltersPanel_js_1.AgentFiltersPanel, { filters: filters, onFiltersChange: setFilters, enableAdvancedFiltering: enableAdvancedFiltering, enableSavedFilters: enableSavedFilters }) })] }), (0, jsx_runtime_1.jsxs)("div", { className: "flex-1 min-w-0", ref: dropTarget, children: [(0, jsx_runtime_1.jsx)("div", { className: "mb-6", children: (0, jsx_runtime_1.jsxs)("div", { className: "flex items-center justify-between", children: [(0, jsx_runtime_1.jsx)(SearchInput_js_1.SearchInput, { ref: searchInputRef, value: searchTerm, onChange: setSearchTerm, placeholder: "Search agents...", enableSemanticSearch: enableSemanticSearch, "aria-label": "Search agents", role: "search" }), enableBulkOperations && selectedAgents.length > 0 && ((0, jsx_runtime_1.jsx)("div", { "data-testid": "bulk-operations-toolbar", children: (0, jsx_runtime_1.jsx)(BulkOperationsToolbar_js_1.BulkOperationsToolbar, { selectedCount: selectedAgents.length, onBulkOperation: handleBulkOperation }) }))] }) }), (0, jsx_runtime_1.jsx)("div", { "data-testid": "agent-profiles-grid", children: renderAgentView() }), totalPages > 1 && ((0, jsx_runtime_1.jsxs)("div", { className: "flex items-center justify-between mt-8", children: [(0, jsx_runtime_1.jsxs)("div", { className: "text-sm text-gray-700", children: ["Showing ", ((currentPage - 1) * maxAgentsPerPage) + 1, " to ", Math.min(currentPage * maxAgentsPerPage, filteredAgents.length), " of ", filteredAgents.length, " agents"] }), (0, jsx_runtime_1.jsxs)("div", { className: "flex space-x-2", children: [(0, jsx_runtime_1.jsx)(Button_js_1.Button, { variant: "outline", onClick: () => setCurrentPage(prev => Math.max(prev - 1, 1)), disabled: currentPage === 1, children: "Previous" }), Array.from({ length: Math.min(totalPages, 5) }, (_, i) => {
                                                const page = Math.max(1, Math.min(totalPages - 4, currentPage - 2)) + i;
                                                return ((0, jsx_runtime_1.jsx)(Button_js_1.Button, { variant: page === currentPage ? 'primary' : 'outline', onClick: () => setCurrentPage(page), children: page }, page));
                                            }), (0, jsx_runtime_1.jsx)(Button_js_1.Button, { variant: "outline", onClick: () => setCurrentPage(prev => Math.min(prev + 1, totalPages)), disabled: currentPage === totalPages, children: "Next" })] })] }))] })] }), showWizard && ((0, jsx_runtime_1.jsx)(Modal_js_1.Modal, { isOpen: showWizard, onClose: () => setShowWizard(false), title: "Create New Agent", size: "large", "data-testid": "agent-wizard-modal", children: (0, jsx_runtime_1.jsx)(AgentCreationWizard_js_1.AgentCreationWizard, { onComplete: (agent) => {
                        setShowWizard(false);
                        onAgentCreate?.(agent);
                    }, onCancel: () => setShowWizard(false), enableConfigValidation: enableConfigValidation }) })), showTesting && selectedAgent && ((0, jsx_runtime_1.jsx)(Modal_js_1.Modal, { isOpen: showTesting, onClose: () => setShowTesting(false), title: `Test Agent - ${selectedAgent.name}`, size: "large", "data-testid": "agent-testing-playground", children: (0, jsx_runtime_1.jsx)(AgentTestingPlayground_js_1.AgentTestingPlayground, { agent: selectedAgent, onClose: () => setShowTesting(false) }) })), showHealth && selectedAgent && ((0, jsx_runtime_1.jsx)(Modal_js_1.Modal, { isOpen: showHealth, onClose: () => setShowHealth(false), title: `Health Monitor - ${selectedAgent.name}`, size: "large", "data-testid": "health-monitoring-panel", children: (0, jsx_runtime_1.jsx)(AgentHealthMonitor_js_1.AgentHealthMonitor, { agent: selectedAgent, onClose: () => setShowHealth(false) }) })), showInsights && selectedAgent && ((0, jsx_runtime_1.jsx)(Modal_js_1.Modal, { isOpen: showInsights, onClose: () => setShowInsights(false), title: `Conversation Insights - ${selectedAgent.name}`, size: "large", "data-testid": "conversation-insights-modal", children: (0, jsx_runtime_1.jsx)(ConversationInsights_js_1.ConversationInsights, { agent: selectedAgent, onClose: () => setShowInsights(false) }) })), showLayoutEditor && ((0, jsx_runtime_1.jsx)(Modal_js_1.Modal, { isOpen: showLayoutEditor, onClose: () => setShowLayoutEditor(false), title: "Customize Layout", size: "fullscreen", "data-testid": "layout-editor", children: (0, jsx_runtime_1.jsx)(LayoutEditor_js_1.LayoutEditor, { currentLayout: layoutMode, onLayoutChange: setLayoutMode, onClose: () => setShowLayoutEditor(false), dragHandlers: dragHandlers }) }))] }));
};
exports.AgentProfiles = AgentProfiles;
//# sourceMappingURL=AgentProfiles.js.map