"use client";

import { useEffect, useState, Suspense } from 'react';
import { useSearchParams, useRouter } from 'next/navigation';
import { ChatWindow } from '@/components/features/chat/chat-window';
import { ChatInput } from '@/components/features/chat/chat-input';
import { DraftSheet } from '@/components/features/journal/draft-sheet';
import { useChatStore } from '@/store/use-chat';
import { ArrowLeft, Bot, Loader2 } from "lucide-react";
import Link from "next/link";
import { LLMService } from '@/services/llm-service';
import { ProviderManagementService } from '@/services/provider-management-service';

function ChatPageContent() {
    const { resetSession, phase } = useChatStore();
    const searchParams = useSearchParams();
    const router = useRouter();

    // Connection Status State
    const [connectionStatus, setConnectionStatus] = useState<'checking' | 'connected' | 'error'>('checking');

    // Check for "new" param to force fresh session
    useEffect(() => {
        if (searchParams.get('new') === 'true') {
            resetSession();
            // Clean URL
            router.replace('/chat');
        }
    }, [searchParams, router, resetSession]);

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

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

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

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

        checkConnection();
    }, []);

    return (
        <div className="flex flex-col h-dvh bg-background relative">
            {/* Session Header */}
            <div className="flex items-center justify-between px-4 py-3 bg-white/80 backdrop-blur border-b border-slate-200 shrink-0 z-10 sticky top-0">
                <div className="flex items-center gap-3">
                    <Link href="/" className="text-slate-500 hover:text-slate-700 transition-colors">
                        <ArrowLeft className="w-5 h-5" />
                    </Link>
                    <div className="flex items-center gap-2 font-medium text-slate-700">
                        <div className="relative">
                            <Bot className="w-5 h-5 text-indigo-600" />
                            <div className={`absolute -bottom-0.5 -right-0.5 w-2.5 h-2.5 rounded-full border-2 border-white ${connectionStatus === 'connected' ? 'bg-green-500' :
                                connectionStatus === 'checking' ? 'bg-yellow-400' : 'bg-red-500'
                                }`} />
                        </div>
                        <span className="font-serif">Teacher</span>
                        {phase === 'drafting' && <span className="text-xs text-indigo-500 animate-pulse ml-2">Simulating...</span>}
                    </div>
                </div>
            </div>

            {/* Chat Messages - Scrollable Area */}
            <div className="flex-1 flex flex-col min-h-0 overflow-hidden relative">
                <ChatWindow />
            </div>

            <DraftSheet />

            {/* Chat Input - Fixed at Bottom */}
            <div className="shrink-0">
                <ChatInput />
            </div>
        </div>
    );
}

export default function ChatPage() {
    return (
        <Suspense fallback={
            <div className="flex flex-col h-dvh bg-background items-center justify-center">
                <Loader2 className="w-8 h-8 animate-spin text-indigo-500" />
            </div>
        }>
            <ChatPageContent />
        </Suspense>
    );
}

