import React, { useState, useEffect, useCallback } from 'react';
import { useAuth } from '../../contexts/AuthContext';
import { ChatView } from '../../../components/views/ChatView';
import { ModelConfig, DEFAULT_MODELS } from '../../../types';
import { modelConfigService } from '../../../services/modelConfigService';

export default function ChatPage() {
    const { apiKey, logout, user } = useAuth();
    const [modelConfigs, setModelConfigs] = useState<ModelConfig[]>(DEFAULT_MODELS);

    const fetchModels = useCallback(async () => {
        if (!apiKey) return;
        try {
            const backendModels = await modelConfigService.getAll(apiKey);
            const map = new Map<string, ModelConfig>();
            DEFAULT_MODELS.forEach(m => map.set(m.id, m));
            backendModels.forEach(m => map.set(m.id, m));
            setModelConfigs(Array.from(map.values()));
        } catch {
            setModelConfigs(DEFAULT_MODELS);
        }
    }, [apiKey]);

    useEffect(() => { fetchModels(); }, [fetchModels]);

    return (
        <ChatView
            authToken={apiKey}
            onLogout={logout}
            modelConfigs={modelConfigs}
            onNavigate={() => { }}
            isAdmin={user?.role === 'TENANT_ADMIN' || user?.role === 'SUPER_ADMIN'}
        />
    );
}

