"use client";

import { useEffect, useRef, useState } from 'react';
import { ChatBubble } from './chat-bubble';
import { TypingIndicator } from './typing-indicator';
import { useChatStore } from '@/store/use-chat';
import { Bot, Sparkles } from 'lucide-react';
import { ProviderManagementService } from '@/services/provider-management-service';

export function ChatWindow() {
    const { messages, isTyping } = useChatStore();
    const bottomRef = useRef<HTMLDivElement>(null);
    const containerRef = useRef<HTMLDivElement>(null);
    const [isUserScrolling, setIsUserScrolling] = useState(false);
    const [connectionStatus, setConnectionStatus] = useState<'checking' | 'connected' | 'error'>('checking');

    // Check connection status
    useEffect(() => {
        const checkConnection = async () => {
            setConnectionStatus('checking');
            const settings = ProviderManagementService.getActiveProviderSettings();

            if (!settings.apiKey) {
                setConnectionStatus('error');
                return;
            }

            const result = await ProviderManagementService.validateConnection(
                settings.baseUrl,
                settings.apiKey,
                settings.modelName
            );

            if (result.isValid) {
                setConnectionStatus('connected');
            } else {
                setConnectionStatus('error');
            }
        };

        checkConnection();
    }, []);

    useEffect(() => {
        if (!isUserScrolling) {
            bottomRef.current?.scrollIntoView({ behavior: 'smooth', block: 'end' });
        }
    }, [messages.length, isUserScrolling, isTyping]);

    // Detect when user is manually scrolling
    useEffect(() => {
        const container = containerRef.current;
        if (!container) return;

        const handleScroll = () => {
            const { scrollTop, scrollHeight, clientHeight } = container;
            const isAtBottom = scrollHeight - scrollTop - clientHeight < 100;

            // If user scrolls up from bottom, disable auto-scroll
            if (!isAtBottom && !isUserScrolling) {
                setIsUserScrolling(true);
            }

            // If user scrolls back near bottom, re-enable auto-scroll
            if (isAtBottom && isUserScrolling) {
                setIsUserScrolling(false);
            }
        };

        container.addEventListener('scroll', handleScroll);
        return () => container.removeEventListener('scroll', handleScroll);
    }, [isUserScrolling]);

    if (!messages || messages.length === 0) {
        return (
            <div className="flex-1 flex flex-col items-center justify-center text-center p-8 space-y-6">
                <div className="relative">
                    <div className="w-32 h-32 bg-gradient-to-br from-secondary to-muted rounded-full flex items-center justify-center">
                        <Bot className="w-16 h-16 text-muted-foreground/50" aria-hidden="true" />
                    </div>
                    <Sparkles className="w-8 h-8 text-amber-400 absolute -top-2 -right-2" aria-hidden="true" />

                    {/* Connection Status Indicator */}
                    <div className={`absolute -bottom-1 -right-1 w-4 h-4 rounded-full border-2 border-white ${connectionStatus === 'connected' ? 'bg-green-500' :
                        connectionStatus === 'checking' ? 'bg-yellow-400 animate-pulse' : 'bg-red-500'
                        }`} />
                </div>

                <div className="space-y-2 max-w-md">
                    <h2 className="text-2xl font-bold font-serif text-foreground">
                        Teacher
                    </h2>
                    <p className="text-muted-foreground font-sans">
                        I'm here to listen. Let it all out.
                    </p>
                    {connectionStatus === 'connected' && (
                        <p className="text-sm text-green-600 dark:text-green-400">
                            Connected and ready
                        </p>
                    )}
                    {connectionStatus === 'error' && (
                        <p className="text-sm text-red-600 dark:text-red-400">
                            Please configure your AI provider in Settings
                        </p>
                    )}
                </div>
            </div>
        );
    }

    return (
        <div ref={containerRef} className="w-full h-full flex-1 min-h-0 overflow-y-auto px-4 py-6">
            <div className="max-w-3xl mx-auto space-y-4">
                {messages.map((msg) => (
                    <ChatBubble key={msg.id} role={msg.role} content={msg.content} />
                ))}

                {isTyping && (
                    <TypingIndicator />
                )}

                <div ref={bottomRef} className="h-4" />
            </div>
        </div>
    );
}
