import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import React from 'react';
import { useTheme } from '../theme';
const DEFAULT_MESSAGE = {
    role: 'user',
    content: 'Describe the task here. Use {{argumentName}} placeholders to reference inputs.'
};
const createArgumentId = () => {
    if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
        return `arg-${crypto.randomUUID()}`;
    }
    return `arg-${Math.random().toString(36).slice(2)}`;
};
const argumentsFromSchema = (schema) => {
    if (!Array.isArray(schema) || schema.length === 0) {
        return [];
    }
    return schema.map(([name, options]) => ({
        id: createArgumentId(),
        name,
        description: typeof options?.description === 'string' ? options.description : undefined,
        required: Boolean(options?.required)
    }));
};
const schemaFromArguments = (argumentsDraft) => {
    return argumentsDraft
        .filter((entry) => entry.name.trim().length > 0)
        .map((entry) => [
        entry.name.trim(),
        {
            type: 'string',
            description: entry.description?.trim() || undefined,
            required: entry.required
        }
    ]);
};
const toDraftState = (template) => {
    if (!template) {
        return {
            name: 'my_prompt',
            title: 'My prompt',
            description: '',
            groupLabel: '',
            arguments: [],
            messages: [DEFAULT_MESSAGE]
        };
    }
    return {
        id: template.id,
        name: template.name,
        title: template.title ?? '',
        description: template.description ?? '',
        groupLabel: template.groupLabel ?? '',
        arguments: argumentsFromSchema(template.argumentsSchema),
        messages: template.messages.length > 0 ? template.messages : [DEFAULT_MESSAGE]
    };
};
const normalizeMessageContent = (content) => {
    if (typeof content !== 'string') {
        return '';
    }
    return content.replace(/\r\n?/g, '\n');
};
const CustomPromptComposer = ({ mode, template, onSubmit, onCancel, isSubmitting = false }) => {
    const theme = useTheme();
    const [draft, setDraft] = React.useState(() => toDraftState(template));
    React.useEffect(() => {
        setDraft(toDraftState(template));
    }, [template]);
    const handleArgumentFieldChange = (id, updates) => {
        setDraft((previous) => ({
            ...previous,
            arguments: previous.arguments.map((argument) => (argument.id === id ? { ...argument, ...updates } : argument))
        }));
    };
    const handleRemoveArgument = (id) => {
        setDraft((previous) => ({
            ...previous,
            arguments: previous.arguments.filter((argument) => argument.id !== id)
        }));
    };
    const handleAddArgument = () => {
        setDraft((previous) => ({
            ...previous,
            arguments: [
                ...previous.arguments,
                {
                    id: createArgumentId(),
                    name: `argument_${previous.arguments.length + 1}`,
                    description: '',
                    required: false
                }
            ]
        }));
    };
    const handleMessageChange = (index, updates) => {
        setDraft((previous) => ({
            ...previous,
            messages: previous.messages.map((message, messageIndex) => {
                if (messageIndex !== index) {
                    return message;
                }
                return {
                    ...message,
                    ...updates,
                    content: updates.content !== undefined
                        ? normalizeMessageContent(updates.content)
                        : message.content
                };
            })
        }));
    };
    const handleAddMessage = () => {
        setDraft((previous) => ({
            ...previous,
            messages: [
                ...previous.messages,
                { role: 'user', content: '' }
            ]
        }));
    };
    const handleRemoveMessage = (index) => {
        setDraft((previous) => {
            if (previous.messages.length <= 1) {
                return previous;
            }
            return {
                ...previous,
                messages: previous.messages.filter((_, messageIndex) => messageIndex !== index)
            };
        });
    };
    const handleSubmit = (event) => {
        event.preventDefault();
        const formData = new FormData(event.currentTarget);
        const name = String(formData.get('prompt-name') ?? '').trim() || draft.name;
        const title = String(formData.get('prompt-title') ?? '').trim();
        const description = String(formData.get('prompt-description') ?? '').trim();
        const groupLabel = String(formData.get('prompt-group') ?? '').trim();
        const payload = {
            name,
            title: title.length > 0 ? title : undefined,
            description: description.length > 0 ? description : undefined,
            groupLabel: groupLabel.length > 0 ? groupLabel : undefined,
            argumentsSchema: schemaFromArguments(draft.arguments),
            messages: draft.messages.map((message) => ({
                ...message,
                content: normalizeMessageContent(message.content)
            }))
        };
        onSubmit(payload);
    };
    const handleCancelClick = () => {
        setDraft(toDraftState(template));
        onCancel();
    };
    // const formTitle = mode === 'create' ? 'Create New Prompt' : 'Edit Prompt'
    const submitLabel = isSubmitting
        ? 'Saving…'
        : mode === 'create'
            ? 'Create Prompt'
            : 'Save Changes';
    return (_jsxs("form", { onSubmit: handleSubmit, className: 'space-y-6', children: [_jsxs("div", { className: 'grid gap-4 sm:grid-cols-2', children: [_jsxs("div", { className: 'space-y-2', children: [_jsx("label", { htmlFor: 'prompt-name', className: theme.chatSettingEditor.label, children: "Command name" }), _jsx("input", { id: 'prompt-name', name: 'prompt-name', type: 'text', required: true, defaultValue: draft.name, className: theme.chatSettings.textarea, placeholder: 'my_prompt' }), _jsx("p", { className: theme.chatSettings.helperText, children: "Appears after the slash (/) in the command palette. Stick to letters, numbers, underscores." })] }), _jsxs("div", { className: 'space-y-2', children: [_jsx("label", { htmlFor: 'prompt-title', className: theme.chatSettingEditor.label, children: "Display title (optional)" }), _jsx("input", { id: 'prompt-title', name: 'prompt-title', type: 'text', defaultValue: draft.title, className: theme.chatSettings.textarea, placeholder: 'Daily standup summary' })] }), _jsxs("div", { className: 'space-y-2 sm:col-span-2', children: [_jsx("label", { htmlFor: 'prompt-description', className: theme.chatSettingEditor.label, children: "Description (optional)" }), _jsx("textarea", { id: 'prompt-description', name: 'prompt-description', defaultValue: draft.description, className: theme.chatSettings.textarea, rows: 3, placeholder: 'Explain what this prompt does so teammates can find it quickly.' })] }), _jsxs("div", { className: 'space-y-2 sm:col-span-2', children: [_jsx("label", { htmlFor: 'prompt-group', className: theme.chatSettingEditor.label, children: "Group label (optional)" }), _jsx("input", { id: 'prompt-group', name: 'prompt-group', type: 'text', defaultValue: draft.groupLabel, className: theme.chatSettings.textarea, placeholder: 'Team templates' })] })] }), _jsxs("div", { className: 'space-y-3', children: [_jsxs("div", { className: 'flex items-center justify-between gap-2', children: [_jsxs("div", { children: [_jsx("h4", { className: 'text-sm font-semibold text-gray-900', children: "Arguments" }), _jsxs("p", { className: 'text-xs text-gray-600', children: ["Collect inputs before running the prompt. These map to ", '{{argument}}', " placeholders."] })] }), _jsx("button", { type: 'button', className: theme.buttons.add, onClick: handleAddArgument, children: "Add argument" })] }), draft.arguments.length === 0 ? (_jsx("p", { className: 'rounded-md border border-dashed border-gray-200 bg-gray-50 px-4 py-3 text-sm text-gray-600', children: "No arguments defined. Add one if your prompt needs additional context." })) : (_jsx("ul", { className: 'space-y-3', children: draft.arguments.map((argument) => (_jsxs("li", { className: 'rounded-xl border border-gray-200 bg-white p-4 shadow-sm', children: [_jsxs("div", { className: 'grid gap-3 sm:grid-cols-2', children: [_jsxs("div", { className: 'space-y-2', children: [_jsx("label", { className: theme.chatSettingEditor.label, children: "Name" }), _jsx("input", { value: argument.name, onChange: (event) => handleArgumentFieldChange(argument.id, { name: event.target.value }), className: theme.chatSettings.textarea, placeholder: 'focus_area' })] }), _jsxs("div", { className: 'space-y-2', children: [_jsx("label", { className: theme.chatSettingEditor.label, children: "Required?" }), _jsxs("select", { value: argument.required ? 'required' : 'optional', onChange: (event) => handleArgumentFieldChange(argument.id, { required: event.target.value === 'required' }), className: 'rounded-md border border-gray-200 bg-white px-2 py-1 text-sm text-gray-900 shadow-sm focus:border-blue-400 focus:outline-none focus:ring-2 focus:ring-blue-200', children: [_jsx("option", { value: 'optional', children: "Optional" }), _jsx("option", { value: 'required', children: "Required" })] })] }), _jsxs("div", { className: 'space-y-2 sm:col-span-2', children: [_jsx("label", { className: theme.chatSettingEditor.label, children: "Description (optional)" }), _jsx("input", { value: argument.description ?? '', onChange: (event) => handleArgumentFieldChange(argument.id, { description: event.target.value }), className: theme.chatSettings.textarea, placeholder: 'Describe how this input should be used.' })] })] }), _jsx("div", { className: 'mt-3 flex justify-end', children: _jsx("button", { type: 'button', className: theme.buttons.dangerOutline, onClick: () => handleRemoveArgument(argument.id), children: "Remove argument" }) })] }, argument.id))) }))] }), _jsxs("div", { className: 'space-y-3', children: [_jsxs("div", { className: 'flex items-center justify-between gap-2', children: [_jsxs("div", { children: [_jsx("h4", { className: 'text-sm font-semibold text-gray-900', children: "Template messages" }), _jsxs("p", { className: 'text-xs text-gray-600', children: ["Compose the conversation scaffold sent to the model. Use ", '{{argument}}', " placeholders to inject inputs."] })] }), _jsx("button", { type: 'button', className: theme.buttons.add, onClick: handleAddMessage, children: "Add message" })] }), _jsx("ul", { className: 'space-y-3', children: draft.messages.map((message, index) => (_jsxs("li", { className: 'rounded-xl border border-gray-200 bg-white p-4 shadow-sm', children: [_jsxs("div", { className: 'flex items-center justify-between gap-3', children: [_jsxs("div", { className: 'space-y-2', children: [_jsx("label", { className: theme.chatSettingEditor.label, children: "Role" }), _jsxs("select", { value: message.role, onChange: (event) => handleMessageChange(index, { role: event.target.value }), className: 'rounded-md border border-gray-200 bg-white px-2 py-1 text-sm text-gray-900 shadow-sm focus:border-blue-400 focus:outline-none focus:ring-2 focus:ring-blue-200', children: [_jsx("option", { value: 'system', children: "System" }), _jsx("option", { value: 'user', children: "User" }), _jsx("option", { value: 'assistant', children: "Assistant" })] })] }), draft.messages.length > 1 ? (_jsx("button", { type: 'button', className: theme.buttons.dangerOutline, onClick: () => handleRemoveMessage(index), children: "Remove" })) : null] }), _jsxs("div", { className: 'mt-3 space-y-2', children: [_jsx("label", { className: theme.chatSettingEditor.label, children: "Content" }), _jsx("textarea", { value: message.content, onChange: (event) => handleMessageChange(index, { content: event.target.value }), rows: 4, className: theme.chatSettings.textarea, placeholder: 'Provide a detailed prompt with {{placeholders}} for inputs.' }), _jsxs("p", { className: theme.chatSettings.helperText, children: ["You can reference arguments like ", _jsx("code", { children: '{{focus_area}}' }), ". The placeholders are replaced before the prompt is sent."] })] })] }, `message-${index}`))) })] }), _jsxs("div", { className: 'flex items-center justify-end gap-2', children: [_jsx("button", { type: 'button', className: theme.buttons.secondary, onClick: handleCancelClick, disabled: isSubmitting, children: "Cancel" }), _jsx("button", { type: 'submit', className: theme.buttons.primary, disabled: isSubmitting, children: submitLabel })] })] }));
};
export default CustomPromptComposer;
