"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ApiTester = 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 Select_1 = require("../forms/Select");
const Textarea_1 = require("../forms/Textarea");
const ApiTester = ({ endpoints = [
    { id: '1', name: 'Chat Completion', method: 'POST', url: '/api/chat/completions' },
    { id: '2', name: 'List Models', method: 'GET', url: '/api/models' },
    { id: '3', name: 'Token Count', method: 'POST', url: '/api/tokens/count' },
], baseUrl = '', defaultHeaders = {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer YOUR_API_KEY',
}, onTest, showHistory = true, maxHistoryItems = 10, }) => {
    const [selectedEndpoint, setSelectedEndpoint] = (0, react_1.useState)(endpoints[0]?.id || '');
    const [headers, setHeaders] = (0, react_1.useState)(JSON.stringify(defaultHeaders, null, 2));
    const [body, setBody] = (0, react_1.useState)('');
    const [result, setResult] = (0, react_1.useState)(null);
    const [history, setHistory] = (0, react_1.useState)([]);
    const [loading, setLoading] = (0, react_1.useState)(false);
    const endpoint = endpoints.find(e => e.id === selectedEndpoint);
    const handleTest = async () => {
        if (!endpoint)
            return;
        setLoading(true);
        try {
            let testResult;
            if (onTest) {
                testResult = await onTest(endpoint, body ? JSON.parse(body) : undefined);
            }
            else {
                // Mock test
                await new Promise(resolve => setTimeout(resolve, 500 + Math.random() * 1000));
                testResult = {
                    status: 200,
                    statusText: 'OK',
                    headers: {
                        'content-type': 'application/json',
                        'x-request-id': `req_${Date.now()}`,
                    },
                    body: {
                        id: `resp_${Date.now()}`,
                        object: endpoint.name.toLowerCase().replace(/\s+/g, '_'),
                        created: Date.now(),
                        model: 'gpt-4',
                        usage: {
                            prompt_tokens: 50,
                            completion_tokens: 100,
                            total_tokens: 150,
                        },
                        choices: endpoint.method === 'POST' ? [{
                                index: 0,
                                message: {
                                    role: 'assistant',
                                    content: 'This is a mock response from the API tester.',
                                },
                                finish_reason: 'stop',
                            }] : undefined,
                        data: endpoint.method === 'GET' ? [
                            { id: 'model-1', name: 'GPT-4' },
                            { id: 'model-2', name: 'Claude-3' },
                        ] : undefined,
                    },
                    duration: 500 + Math.random() * 500,
                    timestamp: new Date(),
                };
            }
            setResult(testResult);
            if (showHistory) {
                setHistory(prev => [testResult, ...prev.slice(0, maxHistoryItems - 1)]);
            }
        }
        catch (error) {
            const errorResult = {
                status: 500,
                statusText: 'Error',
                headers: {},
                body: { error: error instanceof Error ? error.message : 'Unknown error' },
                duration: 0,
                timestamp: new Date(),
            };
            setResult(errorResult);
        }
        finally {
            setLoading(false);
        }
    };
    const getMethodColor = (method) => {
        const colors = {
            GET: 'bg-green-100 text-green-800',
            POST: 'bg-blue-100 text-blue-800',
            PUT: 'bg-yellow-100 text-yellow-800',
            DELETE: 'bg-red-100 text-red-800',
            PATCH: 'bg-purple-100 text-purple-800',
        };
        return colors[method] || 'bg-gray-100 text-gray-800';
    };
    const getStatusColor = (status) => {
        if (status >= 200 && status < 300)
            return 'text-green-600';
        if (status >= 400 && status < 500)
            return 'text-yellow-600';
        return 'text-red-600';
    };
    return ((0, jsx_runtime_1.jsx)(Card_1.Card, { className: "api-tester", children: (0, jsx_runtime_1.jsxs)("div", { className: "p-6", children: [(0, jsx_runtime_1.jsx)("h3", { className: "text-lg font-semibold mb-6", children: "API Endpoint Tester" }), (0, jsx_runtime_1.jsxs)("div", { className: "space-y-6", children: [(0, jsx_runtime_1.jsxs)("div", { children: [(0, jsx_runtime_1.jsx)("label", { className: "block text-sm font-medium text-gray-700 mb-2", children: "Select Endpoint" }), (0, jsx_runtime_1.jsx)(Select_1.Select, { value: selectedEndpoint, onChange: (e) => {
                                        setSelectedEndpoint(e.target.value);
                                        const newEndpoint = endpoints.find(ep => ep.id === e.target.value);
                                        if (newEndpoint?.bodyTemplate) {
                                            setBody(newEndpoint.bodyTemplate);
                                        }
                                    }, className: "w-full", children: endpoints.map(ep => ((0, jsx_runtime_1.jsxs)("option", { value: ep.id, children: [ep.name, " - ", ep.method, " ", ep.url] }, ep.id))) })] }), endpoint && ((0, jsx_runtime_1.jsxs)("div", { className: "bg-gray-50 rounded-lg p-4", children: [(0, jsx_runtime_1.jsxs)("div", { className: "flex items-center gap-3 mb-3", children: [(0, jsx_runtime_1.jsx)("span", { className: `px-3 py-1 rounded-full text-xs font-medium ${getMethodColor(endpoint.method)}`, children: endpoint.method }), (0, jsx_runtime_1.jsxs)("code", { className: "text-sm text-gray-700", children: [baseUrl, endpoint.url] })] }), (0, jsx_runtime_1.jsxs)("div", { className: "mb-4", children: [(0, jsx_runtime_1.jsx)("label", { className: "block text-sm font-medium text-gray-700 mb-2", children: "Headers (JSON)" }), (0, jsx_runtime_1.jsx)(Textarea_1.Textarea, { value: headers, onChange: (e) => setHeaders(e.target.value), rows: 4, className: "font-mono text-xs", placeholder: '{"Authorization": "Bearer YOUR_KEY"}' })] }), (endpoint.method === 'POST' || endpoint.method === 'PUT' || endpoint.method === 'PATCH') && ((0, jsx_runtime_1.jsxs)("div", { children: [(0, jsx_runtime_1.jsx)("label", { className: "block text-sm font-medium text-gray-700 mb-2", children: "Request Body (JSON)" }), (0, jsx_runtime_1.jsx)(Textarea_1.Textarea, { value: body, onChange: (e) => setBody(e.target.value), rows: 6, className: "font-mono text-xs", placeholder: '{"model": "gpt-4", "messages": [{"role": "user", "content": "Hello"}]}' })] }))] })), (0, jsx_runtime_1.jsx)(Button_1.Button, { onClick: handleTest, disabled: loading || !endpoint, variant: "primary", className: "w-full", children: loading ? 'Testing...' : 'Send Request' }), result && ((0, jsx_runtime_1.jsxs)("div", { className: "border rounded-lg", children: [(0, jsx_runtime_1.jsx)("div", { className: "bg-gray-50 px-4 py-3 border-b", children: (0, jsx_runtime_1.jsxs)("div", { className: "flex justify-between items-center", children: [(0, jsx_runtime_1.jsxs)("div", { className: "flex items-center gap-3", children: [(0, jsx_runtime_1.jsxs)("span", { className: `font-medium ${getStatusColor(result.status)}`, children: [result.status, " ", result.statusText] }), (0, jsx_runtime_1.jsxs)("span", { className: "text-sm text-gray-600", children: [result.duration.toFixed(0), "ms"] })] }), (0, jsx_runtime_1.jsx)("span", { className: "text-xs text-gray-500", children: result.timestamp.toLocaleTimeString() })] }) }), (0, jsx_runtime_1.jsxs)("div", { className: "p-4", children: [(0, jsx_runtime_1.jsxs)("div", { className: "mb-4", children: [(0, jsx_runtime_1.jsx)("h5", { className: "text-sm font-medium text-gray-700 mb-2", children: "Response Headers" }), (0, jsx_runtime_1.jsx)("pre", { className: "text-xs bg-gray-100 p-3 rounded overflow-x-auto", children: JSON.stringify(result.headers, null, 2) })] }), (0, jsx_runtime_1.jsxs)("div", { children: [(0, jsx_runtime_1.jsx)("h5", { className: "text-sm font-medium text-gray-700 mb-2", children: "Response Body" }), (0, jsx_runtime_1.jsx)("pre", { className: "text-xs bg-gray-100 p-3 rounded overflow-x-auto", children: JSON.stringify(result.body, null, 2) })] })] })] })), showHistory && history.length > 0 && ((0, jsx_runtime_1.jsxs)("div", { children: [(0, jsx_runtime_1.jsx)("h4", { className: "font-medium text-gray-700 mb-3", children: "Request History" }), (0, jsx_runtime_1.jsx)("div", { className: "space-y-2", children: history.map((item, index) => ((0, jsx_runtime_1.jsxs)("div", { className: "flex items-center justify-between px-3 py-2 bg-gray-50 rounded", children: [(0, jsx_runtime_1.jsxs)("div", { className: "flex items-center gap-3", children: [(0, jsx_runtime_1.jsx)("span", { className: `text-sm font-medium ${getStatusColor(item.status)}`, children: item.status }), (0, jsx_runtime_1.jsx)("span", { className: "text-sm text-gray-600", children: endpoints.find(e => e.url === item.url)?.name || 'API Request' })] }), (0, jsx_runtime_1.jsxs)("div", { className: "flex items-center gap-3 text-sm text-gray-500", children: [(0, jsx_runtime_1.jsxs)("span", { children: [item.duration.toFixed(0), "ms"] }), (0, jsx_runtime_1.jsx)("span", { children: item.timestamp.toLocaleTimeString() })] })] }, index))) })] }))] })] }) }));
};
exports.ApiTester = ApiTester;
exports.default = exports.ApiTester;
//# sourceMappingURL=ApiTester.js.map