import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import React from 'react';
import { useChatSettings } from '../contexts/ChatSettingsContext';
import { useCustomPrompts } from '../contexts/customPrompts/useCustomPrompts';
import { useTheme } from '../theme';
import CustomPromptList from './CustomPromptList';
const DEFAULT_PROMPT_MESSAGE = 'Describe the task here. Use {{argumentName}} placeholders to reference inputs.';
export const ChatSettingsSection = () => {
    const theme = useTheme();
    const { agentPrompt, setAgentPrompt, resetAgentPrompt, attachmentCallbackSource, setAttachmentCallbackSource, resetAttachmentCallbackSource, attachmentCallbackError, isAttachmentCallbackOverridden, isAgentPromptOverridden } = useChatSettings();
    const { templates, readonlyPrompts, createPrompt, updatePrompt, deletePrompt, duplicatePrompt } = useCustomPrompts();
    const [activePromptId, setActivePromptId] = React.useState(null);
    const [isCreatingPrompt, setIsCreatingPrompt] = React.useState(false);
    const [savingPromptId, setSavingPromptId] = React.useState(null);
    const [callbackDraft, setCallbackDraft] = React.useState(attachmentCallbackSource);
    const [callbackStatus, setCallbackStatus] = React.useState('idle');
    React.useEffect(() => {
        setCallbackDraft(attachmentCallbackSource);
    }, [attachmentCallbackSource]);
    React.useEffect(() => {
        if (callbackStatus !== 'saved')
            return;
        if (typeof window === 'undefined')
            return;
        const timeout = window.setTimeout(() => {
            setCallbackStatus('idle');
        }, 2000);
        return () => {
            window.clearTimeout(timeout);
        };
    }, [callbackStatus]);
    const handleCallbackSubmit = React.useCallback((event) => {
        event.preventDefault();
        if (isAttachmentCallbackOverridden) {
            return;
        }
        setAttachmentCallbackSource(callbackDraft);
        setCallbackStatus('saved');
    }, [callbackDraft, setAttachmentCallbackSource, isAttachmentCallbackOverridden]);
    const handleCallbackReset = React.useCallback(() => {
        if (isAttachmentCallbackOverridden) {
            return;
        }
        resetAttachmentCallbackSource();
        setCallbackStatus('idle');
    }, [resetAttachmentCallbackSource, isAttachmentCallbackOverridden]);
    const isCallbackDirty = !isAttachmentCallbackOverridden && callbackDraft !== attachmentCallbackSource;
    const isAttachmentFormDisabled = isAttachmentCallbackOverridden;
    const isPromptDisabled = isAgentPromptOverridden;
    const handlePromptSelect = React.useCallback((id) => {
        setActivePromptId(id);
    }, []);
    const handlePromptCreate = React.useCallback(() => {
        if (isCreatingPrompt) {
            return;
        }
        setIsCreatingPrompt(true);
        try {
            const baseName = `custom_prompt_${Date.now().toString(36)}`;
            const newId = createPrompt({
                name: baseName,
                title: 'Untitled prompt',
                argumentsSchema: [],
                messages: [
                    {
                        role: 'user',
                        content: DEFAULT_PROMPT_MESSAGE
                    }
                ]
            });
            setActivePromptId(newId);
        }
        catch (error) {
            console.error('Failed to create custom prompt', error);
        }
        finally {
            setIsCreatingPrompt(false);
        }
    }, [createPrompt, isCreatingPrompt]);
    const handlePromptDuplicate = React.useCallback((id) => {
        const duplicateId = duplicatePrompt(id);
        if (duplicateId) {
            setActivePromptId(duplicateId);
        }
    }, [duplicatePrompt]);
    const handlePromptDelete = React.useCallback((id) => {
        const removed = deletePrompt(id);
        if (!removed) {
            return;
        }
        if (activePromptId === id) {
            setActivePromptId(null);
        }
    }, [activePromptId, deletePrompt]);
    const handlePromptUpdate = React.useCallback((id, updates) => {
        setSavingPromptId(id);
        try {
            updatePrompt(id, updates);
        }
        finally {
            setSavingPromptId((current) => (current === id ? null : current));
        }
    }, [updatePrompt]);
    React.useEffect(() => {
        setActivePromptId((current) => {
            if (templates.length === 0) {
                return null;
            }
            if (current && templates.some((template) => template.id === current)) {
                return current;
            }
            return templates[0].id;
        });
    }, [templates]);
    return (_jsxs("div", { className: theme.chatSettings.container, children: [_jsxs("div", { className: 'space-y-6', children: [_jsxs("div", { children: [_jsx("h2", { className: theme.chatSettings.heading, children: "Custom Prompts" }), _jsx("p", { className: theme.chatSettings.description, children: "Manage reusable slash command templates and define the arguments they accept." })] }), _jsx(CustomPromptList, { userTemplates: templates, readonlyPrompts: readonlyPrompts, activePromptId: activePromptId, onSelect: handlePromptSelect, onCreate: handlePromptCreate, onDuplicate: handlePromptDuplicate, onDelete: handlePromptDelete, onUpdate: handlePromptUpdate, isCreateDisabled: isCreatingPrompt, savingPromptId: savingPromptId })] }), _jsxs("div", { className: 'space-y-4', children: [_jsxs("div", { children: [_jsx("h2", { className: theme.chatSettings.heading, children: "Agent Prompt" }), _jsx("p", { className: theme.chatSettings.description, children: "Configure the optional system prompt used by the chat agent." })] }), _jsxs("div", { className: 'space-y-2', children: [_jsx("label", { htmlFor: 'chat-agent-prompt', className: theme.chatSettingEditor.label, children: "System instructions (optional)" }), _jsx("textarea", { id: 'chat-agent-prompt', value: agentPrompt, onChange: (event) => setAgentPrompt(event.target.value), rows: 6, className: theme.chatSettings.textarea, disabled: isPromptDisabled, placeholder: 'Provide high-level instructions or leave blank to rely on the model defaults.' }), _jsx("p", { className: theme.chatSettings.helperText, children: "These instructions are passed to the chat agent as system guidance. Leave empty to disable custom prompting." }), isPromptDisabled ? (_jsx("div", { className: theme.systemSettings.infoMessage, children: _jsx("p", { children: "The embedding application supplies the system instructions, so editing is unavailable in the playground." }) })) : null] }), _jsx("div", { children: _jsx("button", { type: 'button', onClick: resetAgentPrompt, disabled: isPromptDisabled, className: `${theme.buttons.smallSecondary} ${isPromptDisabled ? 'disabled:cursor-not-allowed disabled:opacity-60' : ''}`, children: "Reset to default" }) })] }), _jsxs("div", { className: 'space-y-4', children: [_jsxs("div", { children: [_jsx("h2", { className: theme.chatSettings.heading, children: "Attachment Handler" }), _jsxs("p", { className: theme.chatSettings.description, children: ["Provide the code for the ", _jsx("code", { children: "onAttachmentCached" }), " callback invoked after files are cached locally."] })] }), isAttachmentFormDisabled ? (_jsxs("div", { className: theme.systemSettings.infoMessage, children: [_jsx("p", { children: "The attachment handler is configured by the embedding application and can't be edited within the playground." }), _jsx("p", { className: 'mt-2', children: "Update the host configuration to change this behavior." })] })) : (_jsxs("form", { onSubmit: handleCallbackSubmit, className: 'space-y-3', children: [_jsxs("div", { className: 'space-y-2', children: [_jsx("label", { htmlFor: 'chat-attachment-handler', className: theme.chatSettingEditor.label, children: "Attachment callback source" }), _jsx("textarea", { id: 'chat-attachment-handler', value: callbackDraft, onChange: (event) => setCallbackDraft(event.target.value), rows: 10, className: `${theme.chatSettings.textarea} font-mono`, placeholder: 'async (attachment) => {\\n  // Upload the attachment and return a URL\\n  return { sourceUrl: "https://example.com/my-upload" }\\n}' }), _jsxs("p", { className: theme.chatSettings.helperText, children: ["Return an object like ", _jsx("code", { children: '{ sourceUrl?: string }' }), ". The function may be async and receives the cached attachment metadata."] }), attachmentCallbackError ? (_jsxs("p", { className: 'text-xs text-red-500', children: ["Compilation error: ", attachmentCallbackError] })) : null] }), _jsxs("div", { className: 'flex flex-wrap items-center gap-2', children: [_jsx("button", { type: 'submit', disabled: !isCallbackDirty, className: `${theme.buttons.primary} text-xs px-3 py-1 disabled:cursor-not-allowed disabled:opacity-60`, children: "Save handler" }), _jsx("button", { type: 'button', onClick: handleCallbackReset, className: theme.buttons.smallSecondary, children: "Reset to default" }), callbackStatus === 'saved' ? (_jsx("span", { className: theme.statusPill.success, children: "Saved" })) : null] })] }))] })] }));
};
