"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.KnowledgeBase = void 0;
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = require("react");
const Card_1 = require("../common/Card");
const Button_1 = require("../forms/Button");
const Input_1 = require("../forms/Input");
const Select_1 = require("../forms/Select");
const KnowledgeBase = ({ items: initialItems = [], categories = ['General', 'Technical', 'Business', 'FAQ', 'Tutorial'], onAdd, onUpdate, onDelete, onSearch, showStats = true, enableEdit = true, }) => {
    const [items, setItems] = (0, react_1.useState)(initialItems.length > 0 ? initialItems : [
        {
            id: '1',
            title: 'What is an LLM?',
            content: 'A Large Language Model (LLM) is a type of artificial intelligence model trained on vast amounts of text data to understand and generate human-like text. Examples include GPT-4, Claude, and Gemini.',
            category: 'FAQ',
            tags: ['AI', 'LLM', 'basics'],
            source: 'AI Documentation',
            confidence: 0.95,
            lastUpdated: new Date(),
            usageCount: 245,
        },
        {
            id: '2',
            title: 'Prompt Engineering Best Practices',
            content: 'Effective prompt engineering involves: 1) Being specific and clear, 2) Providing context, 3) Breaking down complex tasks, 4) Using examples, 5) Iterating and refining prompts based on outputs.',
            category: 'Tutorial',
            tags: ['prompting', 'best-practices', 'optimization'],
            source: 'Engineering Guide',
            confidence: 0.92,
            lastUpdated: new Date(Date.now() - 86400000),
            usageCount: 189,
        },
        {
            id: '3',
            title: 'API Rate Limits',
            content: 'Our API has the following rate limits: Free tier: 20 requests/minute, Pro tier: 100 requests/minute, Enterprise: Custom limits. Rate limit headers are included in all API responses.',
            category: 'Technical',
            tags: ['API', 'limits', 'pricing'],
            source: 'API Reference',
            confidence: 1.0,
            lastUpdated: new Date(Date.now() - 172800000),
            usageCount: 423,
        },
    ]);
    const [searchQuery, setSearchQuery] = (0, react_1.useState)('');
    const [selectedCategory, setSelectedCategory] = (0, react_1.useState)('all');
    const [selectedItem, setSelectedItem] = (0, react_1.useState)(null);
    const [isAdding, setIsAdding] = (0, react_1.useState)(false);
    const [newItem, setNewItem] = (0, react_1.useState)({
        title: '',
        content: '',
        category: categories[0],
        tags: '',
        source: '',
        confidence: 0.9,
    });
    const filteredItems = (0, react_1.useMemo)(() => {
        let filtered = items;
        if (selectedCategory !== 'all') {
            filtered = filtered.filter(item => item.category === selectedCategory);
        }
        if (searchQuery) {
            const query = searchQuery.toLowerCase();
            filtered = filtered.filter(item => item.title.toLowerCase().includes(query) ||
                item.content.toLowerCase().includes(query) ||
                item.tags.some(tag => tag.toLowerCase().includes(query)));
        }
        return filtered.sort((a, b) => b.usageCount - a.usageCount);
    }, [items, searchQuery, selectedCategory]);
    const stats = (0, react_1.useMemo)(() => {
        return {
            totalItems: items.length,
            totalUsage: items.reduce((sum, item) => sum + item.usageCount, 0),
            avgConfidence: items.reduce((sum, item) => sum + item.confidence, 0) / items.length,
            categoryCounts: categories.reduce((acc, cat) => {
                acc[cat] = items.filter(item => item.category === cat).length;
                return acc;
            }, {}),
        };
    }, [items, categories]);
    const handleAdd = async () => {
        if (!newItem.title || !newItem.content)
            return;
        const itemToAdd = {
            id: Date.now().toString(),
            ...newItem,
            tags: newItem.tags.split(',').map(t => t.trim()).filter(t => t),
            lastUpdated: new Date(),
            usageCount: 0,
        };
        if (onAdd) {
            await onAdd(itemToAdd);
        }
        else {
            setItems([...items, itemToAdd]);
        }
        setNewItem({
            title: '',
            content: '',
            category: categories[0],
            tags: '',
            source: '',
            confidence: 0.9,
        });
        setIsAdding(false);
    };
    const handleDelete = async (id) => {
        if (onDelete) {
            await onDelete(id);
        }
        else {
            setItems(items.filter(item => item.id !== id));
        }
    };
    const getConfidenceColor = (confidence) => {
        if (confidence >= 0.9)
            return 'text-green-600';
        if (confidence >= 0.7)
            return 'text-yellow-600';
        return 'text-red-600';
    };
    return ((0, jsx_runtime_1.jsx)(Card_1.Card, { className: "knowledge-base", children: (0, jsx_runtime_1.jsxs)("div", { className: "p-6", children: [(0, jsx_runtime_1.jsxs)("div", { className: "flex justify-between items-center mb-6", children: [(0, jsx_runtime_1.jsx)("h3", { className: "text-lg font-semibold", children: "Knowledge Base" }), enableEdit && ((0, jsx_runtime_1.jsx)(Button_1.Button, { onClick: () => setIsAdding(true), variant: "primary", size: "sm", children: "Add Knowledge" }))] }), showStats && ((0, jsx_runtime_1.jsxs)("div", { className: "grid grid-cols-2 md:grid-cols-4 gap-4 mb-6", children: [(0, jsx_runtime_1.jsxs)("div", { className: "bg-blue-50 rounded-lg p-3", children: [(0, jsx_runtime_1.jsx)("div", { className: "text-2xl font-bold text-blue-600", children: stats.totalItems }), (0, jsx_runtime_1.jsx)("div", { className: "text-sm text-gray-600", children: "Total Items" })] }), (0, jsx_runtime_1.jsxs)("div", { className: "bg-green-50 rounded-lg p-3", children: [(0, jsx_runtime_1.jsx)("div", { className: "text-2xl font-bold text-green-600", children: stats.totalUsage }), (0, jsx_runtime_1.jsx)("div", { className: "text-sm text-gray-600", children: "Total Usage" })] }), (0, jsx_runtime_1.jsxs)("div", { className: "bg-yellow-50 rounded-lg p-3", children: [(0, jsx_runtime_1.jsxs)("div", { className: "text-2xl font-bold text-yellow-600", children: [(stats.avgConfidence * 100).toFixed(0), "%"] }), (0, jsx_runtime_1.jsx)("div", { className: "text-sm text-gray-600", children: "Avg Confidence" })] }), (0, jsx_runtime_1.jsxs)("div", { className: "bg-purple-50 rounded-lg p-3", children: [(0, jsx_runtime_1.jsx)("div", { className: "text-2xl font-bold text-purple-600", children: Object.values(stats.categoryCounts).reduce((a, b) => Math.max(a, b), 0) }), (0, jsx_runtime_1.jsx)("div", { className: "text-sm text-gray-600", children: "Max Category" })] })] })), (0, jsx_runtime_1.jsxs)("div", { className: "flex gap-4 mb-6", children: [(0, jsx_runtime_1.jsx)(Input_1.Input, { type: "text", value: searchQuery, onChange: (e) => setSearchQuery(e.target.value), placeholder: "Search knowledge base...", className: "flex-1" }), (0, jsx_runtime_1.jsxs)(Select_1.Select, { value: selectedCategory, onChange: (e) => setSelectedCategory(e.target.value), className: "w-48", children: [(0, jsx_runtime_1.jsx)("option", { value: "all", children: "All Categories" }), categories.map(cat => ((0, jsx_runtime_1.jsxs)("option", { value: cat, children: [cat, " (", stats.categoryCounts[cat] || 0, ")"] }, cat)))] })] }), isAdding && ((0, jsx_runtime_1.jsxs)("div", { className: "border rounded-lg p-4 mb-6 bg-gray-50", children: [(0, jsx_runtime_1.jsx)("h4", { className: "font-medium mb-4", children: "Add New Knowledge" }), (0, jsx_runtime_1.jsxs)("div", { className: "space-y-4", children: [(0, jsx_runtime_1.jsx)(Input_1.Input, { type: "text", value: newItem.title, onChange: (e) => setNewItem({ ...newItem, title: e.target.value }), placeholder: "Title" }), (0, jsx_runtime_1.jsx)("textarea", { value: newItem.content, onChange: (e) => setNewItem({ ...newItem, content: e.target.value }), placeholder: "Content", className: "w-full px-3 py-2 border rounded-md", rows: 4 }), (0, jsx_runtime_1.jsxs)("div", { className: "grid grid-cols-2 gap-4", children: [(0, jsx_runtime_1.jsx)(Select_1.Select, { value: newItem.category, onChange: (e) => setNewItem({ ...newItem, category: e.target.value }), children: categories.map(cat => ((0, jsx_runtime_1.jsx)("option", { value: cat, children: cat }, cat))) }), (0, jsx_runtime_1.jsx)(Input_1.Input, { type: "text", value: newItem.tags, onChange: (e) => setNewItem({ ...newItem, tags: e.target.value }), placeholder: "Tags (comma-separated)" })] }), (0, jsx_runtime_1.jsxs)("div", { className: "flex gap-2", children: [(0, jsx_runtime_1.jsx)(Button_1.Button, { onClick: handleAdd, variant: "primary", size: "sm", children: "Add" }), (0, jsx_runtime_1.jsx)(Button_1.Button, { onClick: () => {
                                                setIsAdding(false);
                                                setNewItem({
                                                    title: '',
                                                    content: '',
                                                    category: categories[0],
                                                    tags: '',
                                                    source: '',
                                                    confidence: 0.9,
                                                });
                                            }, variant: "secondary", size: "sm", children: "Cancel" })] })] })] })), (0, jsx_runtime_1.jsx)("div", { className: "space-y-4", children: filteredItems.map(item => ((0, jsx_runtime_1.jsxs)("div", { className: `border rounded-lg p-4 cursor-pointer transition-all ${selectedItem === item.id ? 'border-blue-500 bg-blue-50' : 'hover:border-gray-300'}`, onClick: () => setSelectedItem(selectedItem === item.id ? null : item.id), children: [(0, jsx_runtime_1.jsxs)("div", { className: "flex justify-between items-start mb-2", children: [(0, jsx_runtime_1.jsx)("h4", { className: "font-medium text-gray-900", children: item.title }), (0, jsx_runtime_1.jsxs)("div", { className: "flex items-center gap-2", children: [(0, jsx_runtime_1.jsxs)("span", { className: `text-sm font-medium ${getConfidenceColor(item.confidence)}`, children: [(item.confidence * 100).toFixed(0), "%"] }), enableEdit && ((0, jsx_runtime_1.jsx)("button", { onClick: (e) => {
                                                    e.stopPropagation();
                                                    handleDelete(item.id);
                                                }, className: "text-red-600 hover:text-red-800", children: "\u00D7" }))] })] }), (0, jsx_runtime_1.jsx)("p", { className: "text-sm text-gray-600 mb-3", children: selectedItem === item.id ? item.content :
                                    item.content.length > 150 ? item.content.substring(0, 150) + '...' : item.content }), (0, jsx_runtime_1.jsxs)("div", { className: "flex items-center justify-between", children: [(0, jsx_runtime_1.jsxs)("div", { className: "flex gap-2", children: [(0, jsx_runtime_1.jsx)("span", { className: "px-2 py-1 bg-gray-100 text-gray-700 text-xs rounded", children: item.category }), item.tags.slice(0, 3).map(tag => ((0, jsx_runtime_1.jsx)("span", { className: "px-2 py-1 bg-blue-100 text-blue-700 text-xs rounded", children: tag }, tag))), item.tags.length > 3 && ((0, jsx_runtime_1.jsxs)("span", { className: "text-xs text-gray-500", children: ["+", item.tags.length - 3] }))] }), (0, jsx_runtime_1.jsxs)("div", { className: "flex gap-3 text-xs text-gray-500", children: [(0, jsx_runtime_1.jsxs)("span", { children: ["\uD83D\uDC41 ", item.usageCount] }), (0, jsx_runtime_1.jsx)("span", { children: new Date(item.lastUpdated).toLocaleDateString() })] })] })] }, item.id))) }), filteredItems.length === 0 && ((0, jsx_runtime_1.jsxs)("div", { className: "text-center py-12", children: [(0, jsx_runtime_1.jsx)("div", { className: "text-4xl mb-4", children: "\uD83D\uDCDA" }), (0, jsx_runtime_1.jsx)("p", { className: "text-gray-600", children: "No knowledge items found" }), (0, jsx_runtime_1.jsx)("p", { className: "text-sm text-gray-500 mt-2", children: "Try adjusting your search or filters" })] }))] }) }));
};
exports.KnowledgeBase = KnowledgeBase;
exports.default = exports.KnowledgeBase;
//# sourceMappingURL=KnowledgeBase.js.map