
import React, { useState, useRef, useEffect, useCallback } from 'react';
import { Bot, Send, User, Loader } from 'lucide-react';
import { createChat } from '../services/geminiService';
import type { Chat } from '@google/genai';
import { ChatMessage } from '../types';

const ChatBotView: React.FC = () => {
    const [chat, setChat] = useState<Chat | null>(null);
    const [messages, setMessages] = useState<ChatMessage[]>([]);
    const [userInput, setUserInput] = useState('');
    const [isLoading, setIsLoading] = useState(false);
    const messagesEndRef = useRef<HTMLDivElement>(null);

    useEffect(() => {
        setChat(createChat());
        setMessages([{
            role: 'model',
            parts: [{ text: 'Hello! I am the Codex Assistant. How can I help you today?' }]
        }]);
    }, []);

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

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

    const handleSendMessage = useCallback(async () => {
        if (!userInput.trim() || !chat || isLoading) return;

        const newUserMessage: ChatMessage = { role: 'user', parts: [{ text: userInput }] };
        setMessages(prev => [...prev, newUserMessage]);
        setUserInput('');
        setIsLoading(true);

        try {
            const stream = await chat.sendMessageStream({ message: userInput });
            let modelResponse = '';
            setMessages(prev => [...prev, { role: 'model', parts: [{ text: '' }] }]);

            for await (const chunk of stream) {
                modelResponse += chunk.text;
                setMessages(prev => {
                    const newMessages = [...prev];
                    newMessages[newMessages.length - 1].parts[0].text = modelResponse;
                    return newMessages;
                });
            }
        } catch (error) {
            console.error('Error sending message:', error);
            setMessages(prev => [...prev, { role: 'model', parts: [{ text: 'Sorry, I encountered an error. Please try again.' }] }]);
        } finally {
            setIsLoading(false);
        }
    }, [userInput, chat, isLoading]);


    const Message: React.FC<{ message: ChatMessage }> = ({ message }) => {
        const isModel = message.role === 'model';
        return (
            <div className={`flex items-start gap-4 ${isModel ? '' : 'flex-row-reverse'}`}>
                <div className={`flex-shrink-0 w-10 h-10 rounded-full flex items-center justify-center ${isModel ? 'bg-indigo-600' : 'bg-slate-700'}`}>
                    {isModel ? <Bot className="text-white" /> : <User className="text-white" />}
                </div>
                <div className={`p-4 rounded-xl max-w-lg ${isModel ? 'bg-slate-800' : 'bg-indigo-700'}`}>
                    <p className="whitespace-pre-wrap">{message.parts[0].text}</p>
                </div>
            </div>
        );
    };

    return (
        <div className="h-full flex flex-col">
            <header className="border-b border-slate-700 pb-4 mb-4">
                <h1 className="text-3xl font-bold text-white">Codex Assistant</h1>
                <p className="mt-1 text-slate-400">Engage in a conversation with a Gemini-powered chat bot.</p>
            </header>
            <div className="flex-1 overflow-y-auto pr-4 space-y-6">
                {messages.map((msg, index) => <Message key={index} message={msg} />)}
                {isLoading && (
                     <div className="flex items-start gap-4">
                        <div className="flex-shrink-0 w-10 h-10 rounded-full flex items-center justify-center bg-indigo-600">
                           <Bot className="text-white" />
                        </div>
                        <div className="p-4 rounded-xl max-w-lg bg-slate-800 flex items-center">
                            <Loader text="Thinking..." />
                        </div>
                    </div>
                )}
                <div ref={messagesEndRef} />
            </div>
            <div className="mt-6 flex items-center gap-4">
                <input
                    type="text"
                    value={userInput}
                    onChange={(e) => setUserInput(e.target.value)}
                    onKeyPress={(e) => e.key === 'Enter' && handleSendMessage()}
                    placeholder="Ask a question..."
                    className="flex-1 bg-slate-800 border border-slate-700 rounded-lg px-4 py-3 focus:ring-2 focus:ring-indigo-500 focus:outline-none"
                    disabled={isLoading}
                />
                <button
                    onClick={handleSendMessage}
                    disabled={isLoading || !userInput.trim()}
                    className="bg-indigo-600 text-white p-3 rounded-lg disabled:bg-indigo-900 disabled:cursor-not-allowed hover:bg-indigo-700 transition-colors"
                >
                    <Send />
                </button>
            </div>
        </div>
    );
};

export default ChatBotView;
