import React, { useState } from 'react';
import { Dialog } from 'primereact/dialog';
import { InputText } from 'primereact/inputtext';
import { Button } from 'primereact/button';
import { ScrollPanel } from 'primereact/scrollpanel';

interface Message {
    role: 'user' | 'assistant';
    content: string;
}

interface ChatGptModalProps {
    visible: boolean;
    onHide: () => void;
}

const ChatGptModal: React.FC<ChatGptModalProps> = ({ visible, onHide }) => {
    const [prompt, setPrompt] = useState('');
    const [messages, setMessages] = useState<Message[]>([]);
    const [loading, setLoading] = useState(false);

    const handleSubmit = async () => {
        if (!prompt.trim()) return;

        setLoading(true);
        const userMessage: Message = { role: 'user', content: prompt };
        setMessages(prev => [...prev, userMessage]);

        try {
            const response = await fetch('/canvas-api/chatgpt/completions', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    data: prompt,
                }),
            });

            const data = await response.json();

            if (data.errorMessage) {
                throw new Error(data.errorMessage);
            }

            const assistantMessage: Message = {
                role: 'assistant',
                content: typeof data.responseText === 'string'
                    ? data.responseText
                    : JSON.stringify(data.responseText, null, 2)
            };

            setMessages(prev => [...prev, assistantMessage]);
        } catch (error) {
            console.error('Error:', error);
            const errorMessage: Message = {
                role: 'assistant',
                content: `Error: ${error instanceof Error ? error.message : 'Failed to get response'}`
            };
            setMessages(prev => [...prev, errorMessage]);
        } finally {
            setLoading(false);
            setPrompt('');
        }
    };

    const handleKeyPress = (e: React.KeyboardEvent) => {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            handleSubmit();
        }
    };

    return (
        <Dialog
            visible={visible}
            onHide={onHide}
            header="ChatGPT Assistant"
            style={{ width: '50vw' }}
            className="chatgpt-modal"
        >
            <div className="flex flex-col h-[60vh]">
                <ScrollPanel style={{ width: '100%', height: 'calc(100% - 60px)' }} className="mb-4">
                    <div className="flex flex-col gap-4 p-4">
                        {messages.map((message, index) => (
                            <div
                                key={index}
                                className={`p-3 rounded-lg max-w-[80%] ${message.role === 'user'
                                        ? 'bg-blue-100 ml-auto'
                                        : 'bg-gray-100'
                                    }`}
                            >
                                <p className="whitespace-pre-wrap">{message.content}</p>
                            </div>
                        ))}
                    </div>
                </ScrollPanel>

                <div className="flex gap-2 mt-auto">
                    <InputText
                        value={prompt}
                        onChange={(e) => setPrompt(e.target.value)}
                        onKeyPress={handleKeyPress}
                        placeholder="Type your message..."
                        className="flex-1"
                        disabled={loading}
                    />
                    <Button
                        icon="pi pi-send"
                        onClick={handleSubmit}
                        loading={loading}
                        disabled={!prompt.trim() || loading}
                    />
                </div>
            </div>
        </Dialog>
    );
};

export default ChatGptModal; 