/**
 * ChatbotPage
 * 
 * Simple chatbot interface - temporary global page.
 * TODO: Migrate to feature instance.
 */

import React, { useState, useEffect, useRef } from 'react';
import styles from './MigratePages.module.css';

interface Message {
    id: string;
    role: 'user' | 'assistant' | 'system';
    content: string;
    timestamp: Date;
}

export const ChatbotPage: React.FC = () => {
    const [messages, setMessages] = useState<Message[]>([]);
    const [inputValue, setInputValue] = useState('');
    const [isLoading, setIsLoading] = useState(false);
    const messagesEndRef = useRef<HTMLDivElement>(null);

    const scrollToBottom = () => {
        messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
    };

    useEffect(() => {
        scrollToBottom();
    }, [messages]);

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        if (!inputValue.trim() || isLoading) return;

        const userMessage: Message = {
            id: Date.now().toString(),
            role: 'user',
            content: inputValue,
            timestamp: new Date()
        };

        setMessages(prev => [...prev, userMessage]);
        setInputValue('');
        setIsLoading(true);

        // Simulate API call - replace with actual chatbot API
        try {
            // TODO: Replace with actual chatbot API call
            await new Promise(resolve => setTimeout(resolve, 1000));
            
            const assistantMessage: Message = {
                id: (Date.now() + 1).toString(),
                role: 'assistant',
                content: 'Dies ist eine Platzhalter-Antwort. Der Chatbot wird zu einer Feature-Instanz migriert.',
                timestamp: new Date()
            };
            
            setMessages(prev => [...prev, assistantMessage]);
        } catch (error) {
            console.error('Error:', error);
        } finally {
            setIsLoading(false);
        }
    };

    return (
        <div className={styles.page}>
            <header className={styles.header}>
                <h1>Chatbot</h1>
                <p className={styles.subtitle}>
                    <span className={styles.migrateTag}>MIGRATE TO FEATURE</span>
                    Einfache Chat-Oberfläche
                </p>
            </header>

            <main className={styles.chatContainer}>
                <div className={styles.messagesArea}>
                    {messages.length === 0 ? (
                        <div className={styles.emptyChat}>
                            <p>Noch keine Nachrichten. Starten Sie eine Konversation!</p>
                        </div>
                    ) : (
                        messages.map(message => (
                            <div 
                                key={message.id} 
                                className={`${styles.message} ${styles[message.role]}`}
                            >
                                <div className={styles.messageContent}>
                                    {message.content}
                                </div>
                                <div className={styles.messageTime}>
                                    {message.timestamp.toLocaleTimeString('de-DE')}
                                </div>
                            </div>
                        ))
                    )}
                    {isLoading && (
                        <div className={`${styles.message} ${styles.assistant}`}>
                            <div className={styles.typing}>
                                <span></span><span></span><span></span>
                            </div>
                        </div>
                    )}
                    <div ref={messagesEndRef} />
                </div>

                <form onSubmit={handleSubmit} className={styles.inputArea}>
                    <input
                        type="text"
                        value={inputValue}
                        onChange={(e) => setInputValue(e.target.value)}
                        placeholder="Nachricht eingeben..."
                        disabled={isLoading}
                        className={styles.chatInput}
                    />
                    <button 
                        type="submit" 
                        disabled={!inputValue.trim() || isLoading}
                        className={styles.sendButton}
                    >
                        Senden
                    </button>
                </form>
            </main>
        </div>
    );
};

export default ChatbotPage;
