import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import React from 'react';
import { buildInfo } from '../config/buildInfo';
import { useTheme } from '../theme';
import { SystemToolList } from './SystemToolList';
const STATIC_KEYS = [
    'chat-agent-prompt',
    'chat-tool-calls-visible',
    'llm-models',
    'mcp-server-options',
    'chat-sessions:index',
    'additional-tool-preferences'
];
const EXPORT_KEYS = [
    'chat-attachment-callback-source',
    'chat-sessions:index',
    'llm-models',
    'mcp-server-options',
    'dashboard:theme-preference',
    'additional-tool-preferences'
];
const PREFIX_KEYS = ['chat-session-', 'chat-sessions:'];
const clearPlaygroundStorage = () => {
    if (typeof window === 'undefined' || !window.localStorage) {
        return { removed: 0 };
    }
    let removed = 0;
    for (const key of STATIC_KEYS) {
        if (window.localStorage.getItem(key) !== null) {
            window.localStorage.removeItem(key);
            removed += 1;
        }
    }
    for (let index = window.localStorage.length - 1; index >= 0; index -= 1) {
        const key = window.localStorage.key(index);
        if (!key)
            continue;
        if (PREFIX_KEYS.some((prefix) => key.startsWith(prefix))) {
            window.localStorage.removeItem(key);
            removed += 1;
        }
    }
    return { removed };
};
export const SystemSettingsSection = () => {
    const [status, setStatus] = React.useState('idle');
    const [feedback, setFeedback] = React.useState('');
    const [importStatus, setImportStatus] = React.useState('idle');
    const [importFeedback, setImportFeedback] = React.useState('');
    const { version, sourceLink, hasSourceLink } = buildInfo;
    const theme = useTheme();
    const fileInputRef = React.useRef(null);
    const handleClearStorage = React.useCallback(() => {
        if (typeof window === 'undefined') {
            setStatus('error');
            setFeedback('Local storage is not available in this environment.');
            return;
        }
        const confirmed = window.confirm('This will remove saved chat sessions, model configurations, and MCP server settings from your browser. Continue?');
        if (!confirmed) {
            return;
        }
        setStatus('pending');
        try {
            const { removed } = clearPlaygroundStorage();
            setStatus('success');
            if (removed > 0) {
                setFeedback('Local storage cleared. Reload the page to start fresh.');
            }
            else {
                setFeedback('No stored data was found to remove.');
            }
        }
        catch (error) {
            console.error('Failed to clear local storage', error);
            setStatus('error');
            setFeedback('Unable to delete local storage. Check the console for details.');
        }
    }, []);
    const handleExportSettings = React.useCallback(() => {
        if (typeof window === 'undefined' || !window.localStorage) {
            setImportStatus('error');
            setImportFeedback('Local storage is not available in this environment.');
            return;
        }
        const payload = {
            version: 1,
            exportedAt: new Date().toISOString(),
            entries: {}
        };
        const exportKeys = new Set(EXPORT_KEYS);
        for (const key of EXPORT_KEYS) {
            payload.entries[key] = window.localStorage.getItem(key);
        }
        for (let index = 0; index < window.localStorage.length; index += 1) {
            const key = window.localStorage.key(index);
            if (!key)
                continue;
            if (key.startsWith('chat-session-') || key.startsWith('chat-sessions:')) {
                if (!exportKeys.has(key)) {
                    payload.entries[key] = window.localStorage.getItem(key);
                }
            }
        }
        const blob = new Blob([JSON.stringify(payload, null, 2)], { type: 'application/json' });
        const url = URL.createObjectURL(blob);
        const anchor = document.createElement('a');
        const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
        anchor.href = url;
        anchor.download = `mcp-playground-settings-${timestamp}.json`;
        document.body.appendChild(anchor);
        anchor.click();
        document.body.removeChild(anchor);
        URL.revokeObjectURL(url);
        setImportStatus('success');
        setImportFeedback('Settings exported as JSON file.');
    }, []);
    const applyImportedSettings = React.useCallback((entries) => {
        if (typeof window === 'undefined' || !window.localStorage) {
            throw new Error('Local storage is not available in this environment.');
        }
        for (const key of EXPORT_KEYS) {
            window.localStorage.removeItem(key);
        }
        for (let index = window.localStorage.length - 1; index >= 0; index -= 1) {
            const key = window.localStorage.key(index);
            if (!key)
                continue;
            if (key.startsWith('chat-session-') || key.startsWith('chat-sessions:')) {
                window.localStorage.removeItem(key);
            }
        }
        Object.entries(entries).forEach(([key, value]) => {
            try {
                if (typeof value === 'string') {
                    window.localStorage.setItem(key, value);
                }
                else if (value === null || value === undefined) {
                    window.localStorage.removeItem(key);
                }
                else {
                    window.localStorage.setItem(key, JSON.stringify(value));
                }
            }
            catch (err) {
                console.error(`Failed to store key ${key}`, err);
            }
        });
    }, []);
    const handleImportSettings = React.useCallback((event) => {
        const file = event.target.files?.[0];
        if (!file)
            return;
        setImportStatus('pending');
        setImportFeedback('');
        const reader = new FileReader();
        reader.onload = () => {
            try {
                const raw = reader.result;
                if (typeof raw !== 'string') {
                    throw new Error('Unable to read file contents as text.');
                }
                const parsed = JSON.parse(raw);
                const entries = typeof parsed.entries === 'object' && parsed.entries !== null
                    ? parsed.entries
                    : parsed;
                applyImportedSettings(entries);
                setImportStatus('success');
                setImportFeedback('Settings imported. Reload the page to apply changes.');
            }
            catch (error) {
                console.error('Failed to import settings', error);
                setImportStatus('error');
                setImportFeedback('Failed to import settings. Ensure the file is a valid JSON export.');
            }
            finally {
                if (fileInputRef.current) {
                    fileInputRef.current.value = '';
                }
            }
        };
        reader.onerror = () => {
            console.error('Failed to read settings file', reader.error);
            setImportStatus('error');
            setImportFeedback('Unable to read the selected file.');
            if (fileInputRef.current) {
                fileInputRef.current.value = '';
            }
        };
        reader.readAsText(file);
    }, [applyImportedSettings]);
    const triggerImportDialog = React.useCallback(() => {
        if (typeof window === 'undefined') {
            setImportStatus('error');
            setImportFeedback('File import is not available in this environment.');
            return;
        }
        fileInputRef.current?.click();
    }, []);
    React.useEffect(() => {
        if (typeof window === 'undefined') {
            return;
        }
        if (status !== 'success' && status !== 'error') {
            return;
        }
        const timer = window.setTimeout(() => {
            setStatus('idle');
            setFeedback('');
        }, 6000);
        return () => window.clearTimeout(timer);
    }, [status]);
    React.useEffect(() => {
        if (typeof window === 'undefined') {
            return;
        }
        if (importStatus !== 'success' && importStatus !== 'error') {
            return;
        }
        const timer = window.setTimeout(() => {
            setImportStatus('idle');
            setImportFeedback('');
        }, 6000);
        return () => window.clearTimeout(timer);
    }, [importStatus]);
    return (_jsxs("div", { className: theme.systemSettings.container, children: [_jsxs("div", { className: theme.systemSettings.headingGroup, children: [_jsx("h2", { className: theme.systemSettings.heading, children: "System Settings" }), _jsx("p", { className: theme.systemSettings.description, children: "Manage application-level data stored in this browser." })] }), _jsxs("div", { className: theme.systemSettings.card, children: [_jsxs("div", { className: 'space-y-1', children: [_jsx("h3", { className: theme.systemSettings.cardHeading, children: "Function Tools" }), _jsx("p", { className: theme.systemSettings.cardSubheading, children: "Modify tool function features for chat sessions." })] }), _jsx("div", { className: 'flex flex-wrap items-center gap-3', children: _jsx(SystemToolList, {}) })] }), _jsxs("div", { className: theme.systemSettings.card, children: [_jsxs("div", { className: 'space-y-1', children: [_jsx("h3", { className: theme.systemSettings.cardHeading, children: "Delete Local Storage" }), _jsx("p", { className: theme.systemSettings.cardSubheading, children: "Clears saved chat history, model preferences, and MCP server configurations used by this playground." })] }), _jsxs("div", { className: 'flex flex-wrap items-center gap-3', children: [_jsx("button", { type: 'button', onClick: handleClearStorage, disabled: status === 'pending', className: theme.systemSettings.primaryAction, children: status === 'pending' ? 'Deleting…' : 'Delete Local Storage' }), _jsx("span", { className: theme.systemSettings.dangerNotice, children: "This action cannot be undone." })] }), status === 'success' && feedback && (_jsx("p", { className: theme.systemSettings.successMessage, children: feedback })), status === 'error' && feedback && (_jsx("p", { className: theme.systemSettings.errorMessage, children: feedback })), status === 'idle' && feedback && (_jsx("p", { className: theme.systemSettings.infoMessage, children: feedback }))] }), _jsxs("div", { className: theme.systemSettings.card, children: [_jsxs("div", { className: 'space-y-1', children: [_jsx("h3", { className: theme.systemSettings.cardHeading, children: "Import / Export Settings" }), _jsx("p", { className: theme.systemSettings.cardSubheading, children: "Download your MCP playground configuration or restore it from a JSON backup. Importing replaces existing values for saved sessions and server options." })] }), _jsxs("div", { className: 'flex flex-wrap items-center gap-3', children: [_jsx("button", { type: 'button', onClick: handleExportSettings, className: theme.systemSettings.secondaryAction, children: "Export settings" }), _jsx("input", { ref: fileInputRef, type: 'file', accept: 'application/json', className: 'hidden', onChange: handleImportSettings }), _jsx("button", { type: 'button', onClick: triggerImportDialog, disabled: importStatus === 'pending', className: theme.systemSettings.secondaryAction, children: importStatus === 'pending' ? 'Importing…' : 'Import settings' }), _jsx("span", { className: theme.systemSettings.helperText, children: "Overrides existing saved settings." })] }), importStatus === 'success' && importFeedback && (_jsx("p", { className: theme.systemSettings.successMessage, children: importFeedback })), importStatus === 'error' && importFeedback && (_jsx("p", { className: theme.systemSettings.errorMessage, children: importFeedback })), importStatus === 'idle' && importFeedback && (_jsx("p", { className: theme.systemSettings.infoMessage, children: importFeedback })), importStatus === 'pending' && !importFeedback && (_jsx("p", { className: theme.systemSettings.infoMessage, children: "Processing settings file\u2026" }))] }), (version || hasSourceLink) && (_jsxs("div", { className: theme.systemSettings.card, children: [_jsxs("div", { className: 'space-y-1', children: [_jsx("h3", { className: theme.systemSettings.cardHeading, children: "Build Information" }), _jsx("p", { className: theme.systemSettings.cardSubheading, children: "Metadata about the current playground bundle." })] }), _jsxs("dl", { className: theme.systemSettings.metaList, children: [version && (_jsxs("div", { className: theme.systemSettings.metaEntry, children: [_jsx("dt", { className: theme.systemSettings.metaLabel, children: "Version" }), _jsxs("dd", { className: theme.systemSettings.metaBadge, children: ["v", version] })] })), hasSourceLink && (_jsxs("div", { className: theme.systemSettings.metaEntry, children: [_jsx("dt", { className: theme.systemSettings.metaLabel, children: "Source" }), _jsx("dd", { className: theme.systemSettings.metaValue, children: _jsx("a", { href: sourceLink, className: theme.buttons.link, target: '_blank', rel: 'noreferrer noopener', children: "Repository" }) })] }))] })] }))] }));
};
export default SystemSettingsSection;
