import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import React from 'react';
import ZodSchemaForm, { lightTheme, darkTheme } from 'zod-schema-form';
import { useTheme, useThemeName } from '../theme';
export const inlinePromptEditorSchema = [
    [
        'name',
        {
            type: 'string',
            label: 'Command name',
            description: 'Unique identifier used when referencing the prompt.',
            required: true,
            minLength: 1
        }
    ],
    [
        'title',
        {
            type: 'string',
            label: 'Display title',
            description: 'Optional friendly label shown in the UI.',
            required: false
        }
    ],
    [
        'description',
        {
            type: 'string',
            label: 'Description',
            description: 'Explain what this prompt should do.',
            required: false
        }
    ],
    [
        'groupLabel',
        {
            type: 'string',
            label: 'Group label',
            description: 'Optional grouping used to organize prompts.',
            required: false
        }
    ],
    [
        'arguments',
        {
            type: 'array',
            label: 'Arguments',
            description: 'Map form inputs to {{argument}} placeholders.',
            minItems: 0,
            items: {
                type: 'object',
                label: 'Argument',
                properties: {
                    name: {
                        type: 'string',
                        label: 'Name',
                        description: 'Placeholder identifier used within messages.',
                        required: true,
                        minLength: 1
                    },
                    description: {
                        type: 'string',
                        label: 'Description',
                        description: 'Describe the expected user input.',
                        required: false
                    },
                    required: {
                        type: 'boolean',
                        label: 'Required?',
                        description: 'Marks whether this input is mandatory.',
                        default: false
                    }
                }
            }
        }
    ],
    [
        'messages',
        {
            type: 'array',
            label: 'Template messages',
            description: 'Craft the conversational scaffolding sent to the model.',
            minItems: 1,
            items: {
                type: 'object',
                label: 'Message',
                properties: {
                    role: {
                        type: 'string',
                        label: 'Role',
                        description: 'Select the role for this message.',
                        enum: ['system', 'user', 'assistant'],
                        required: true,
                        default: 'user'
                    },
                    content: {
                        type: 'string',
                        label: 'Content',
                        description: 'Supports {{placeholders}} to reference collected inputs.',
                        required: true
                    }
                }
            }
        }
    ]
];
const DEFAULT_MESSAGE = { role: 'user', content: '' };
const normalizeMessageContent = (content) => content.replace(/\r\n?/g, '\n');
const argumentsFromSchema = (schema) => {
    if (!Array.isArray(schema)) {
        return [];
    }
    return schema.map(([name, options]) => ({
        name,
        description: typeof options?.description === 'string' ? options.description : undefined,
        required: Boolean(options?.required)
    }));
};
const schemaFromArguments = (drafts) => {
    return drafts
        .filter((argument) => argument.name.trim().length > 0)
        .map((argument) => [
        argument.name.trim(),
        {
            type: 'string',
            description: argument.description?.trim() || undefined,
            required: argument.required
        }
    ]);
};
const toDraftState = (template) => {
    const messages = template.messages.length > 0
        ? template.messages
        : [{ ...DEFAULT_MESSAGE }];
    return {
        name: template.name,
        title: template.title ?? '',
        description: template.description ?? '',
        groupLabel: template.groupLabel ?? '',
        arguments: argumentsFromSchema(template.argumentsSchema),
        messages: messages.map((message) => ({
            role: message.role,
            content: normalizeMessageContent(message.content)
        }))
    };
};
const InlinePromptEditor = ({ template, onSubmit, onCancel, isSubmitting = false }) => {
    const theme = useTheme();
    const themeName = useThemeName();
    const initialValues = React.useMemo(() => toDraftState(template), [template]);
    const formKey = React.useMemo(() => `${template.id}:${template.updatedAt}`, [template.id, template.updatedAt]);
    const handleSubmit = React.useCallback((values) => {
        const trimmedName = values.name.trim();
        const trimmedTitle = values.title?.trim() ?? '';
        const trimmedDescription = values.description?.trim() ?? '';
        const trimmedGroupLabel = values.groupLabel?.trim() ?? '';
        const argumentValues = Array.isArray(values.arguments) ? values.arguments : [];
        const messageValues = Array.isArray(values.messages) ? values.messages : [];
        const payload = {
            name: trimmedName.length > 0 ? trimmedName : template.name,
            title: trimmedTitle.length > 0 ? trimmedTitle : undefined,
            description: trimmedDescription.length > 0 ? trimmedDescription : undefined,
            groupLabel: trimmedGroupLabel.length > 0 ? trimmedGroupLabel : undefined,
            argumentsSchema: schemaFromArguments(argumentValues),
            messages: messageValues.map((message) => ({
                role: message.role,
                content: normalizeMessageContent(message.content)
            }))
        };
        onSubmit(payload);
        if (onCancel) {
            onCancel();
        }
    }, [onSubmit, onCancel, template]);
    return (_jsxs("div", { className: 'space-y-5', children: [_jsx(ZodSchemaForm, { schema: inlinePromptEditorSchema, initialValues: initialValues, onSubmit: handleSubmit, submitButtonText: isSubmitting ? 'Saving…' : 'Save prompt', isSubmitting: isSubmitting, theme: themeName === 'dark' ? darkTheme : lightTheme }, formKey), onCancel ? (_jsx("div", { className: 'flex flex-wrap items-center justify-end gap-2', children: _jsx("button", { type: 'button', className: theme.buttons.secondary, onClick: onCancel, disabled: isSubmitting, children: "Cancel" }) })) : null] }));
};
export default InlinePromptEditor;
