import { useState } from 'react';
import { Dialog } from 'primereact/dialog';
import { InputText } from 'primereact/inputtext';
import { Dropdown } from 'primereact/dropdown';
import { Button } from 'primereact/button';
import { Toast } from 'primereact/toast';
import { useRef } from 'react';
import { api } from '../../services/api';
import { InputTextarea } from 'primereact/inputtextarea';

interface PromptCreatorModalProps {
    visible: boolean;
    onHide: () => void;
    appId: number;
}

const promptTypes = [
    { label: 'API Documentation', value: 'api_documentation' },
    { label: 'Endpoint Analysis', value: 'endpoint_analysis' },
    { label: 'Schema Generation', value: 'schema_generation' },
    { label: 'Custom', value: 'custom' }
];

export default function PromptCreatorModal({ visible, onHide, appId }: PromptCreatorModalProps) {
    const [name, setName] = useState('');
    const [content, setContent] = useState('');
    const [type, setType] = useState<string | null>(null);
    const [loading, setLoading] = useState(false);
    const toast = useRef<Toast>(null);

    const handleSubmit = async () => {
        if (!name || !content || !type) {
            toast.current?.show({
                severity: 'error',
                summary: 'Error',
                detail: 'Please fill in all required fields',
                life: 3000
            });
            return;
        }

        setLoading(true);
        try {
            const response = await api('post', '/api/v1/prompts', {
                name,
                content,
                type,
                appId,
                metadata: {
                    source: 'canvas-api',
                    timestamp: new Date().toISOString()
                }
            });

            toast.current?.show({
                severity: 'success',
                summary: 'Success',
                detail: 'Prompt created successfully',
                life: 3000
            });

            // Process the prompt immediately
            await api('post', `/api/v1/prompts/${response.data.id}/process`);

            // Reset form
            setName('');
            setContent('');
            setType(null);
            onHide();
        } catch (error) {
            console.error('Error creating prompt:', error);
            toast.current?.show({
                severity: 'error',
                summary: 'Error',
                detail: 'Failed to create prompt',
                life: 3000
            });
        } finally {
            setLoading(false);
        }
    };

    return (
        <>
            <Toast ref={toast} />
            <Dialog
                visible={visible}
                onHide={onHide}
                header="Create New Prompt"
                style={{ width: '50vw' }}
                footer={
                    <div className="flex justify-end gap-2">
                        <Button
                            label="Cancel"
                            icon="pi pi-times"
                            onClick={onHide}
                            className="p-button-text"
                        />
                        <Button
                            label="Create"
                            icon="pi pi-check"
                            onClick={handleSubmit}
                            loading={loading}
                            disabled={!name || !content || !type}
                        />
                    </div>
                }
            >
                <div className="flex flex-col gap-4 p-4">
                    <div className="field">
                        <label htmlFor="name" className="block text-sm font-medium text-gray-700 mb-1">
                            Prompt Name
                        </label>
                        <InputText
                            id="name"
                            value={name}
                            onChange={(e) => setName(e.target.value)}
                            className="w-full"
                            placeholder="Enter a name for your prompt..."
                        />
                    </div>
                    <div className="field">
                        <label htmlFor="type" className="block text-sm font-medium text-gray-700 mb-1">
                            Prompt Type
                        </label>
                        <Dropdown
                            id="type"
                            value={type}
                            options={promptTypes}
                            onChange={(e) => setType(e.value)}
                            placeholder="Select a type"
                            className="w-full"
                        />
                    </div>
                    <div className="field">
                        <label htmlFor="content" className="block text-sm font-medium text-gray-700 mb-1">
                            Prompt Content
                        </label>
                        <InputTextarea
                            id="content"
                            value={content}
                            onChange={(e) => setContent(e.target.value)}
                            className="w-full"
                            rows={8}
                            autoResize
                            placeholder="Enter your prompt..."
                        />
                    </div>
                </div>
            </Dialog>
        </>
    );
} 