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

interface SettingsPageProps {
    initialTab?: 'general' | 'user' | 'model' | 'tenants' | 'knowledge_base';
}

export default function SettingsPage({ initialTab }: SettingsPageProps) {
    const { apiKey, 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]);

    const handleUpdateModels = useCallback(async (action: 'create' | 'update' | 'delete', model: ModelConfig) => {
        if (!apiKey) return;
        if (action === 'create') await modelConfigService.create(apiKey, model);
        else if (action === 'update') await modelConfigService.update(apiKey, model.id, model);
        else if (action === 'delete') await modelConfigService.remove(apiKey, model.id);
        await fetchModels();
    }, [apiKey, fetchModels]);

    return (
        <SettingsView
            models={modelConfigs}
            onUpdateModels={handleUpdateModels}
            authToken={apiKey}
            isAdmin={user?.role === 'TENANT_ADMIN' || user?.role === 'SUPER_ADMIN'}
            currentUser={user}
            initialTab={initialTab}
        />
    );
}
