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, activeTenant } = 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;
        const { id, ...data } = model;
        if (action === 'create') await modelConfigService.create(apiKey, data);
        else if (action === 'update') await modelConfigService.update(apiKey, id, data);
        else if (action === 'delete') await modelConfigService.remove(apiKey, id);
        await fetchModels();
    }, [apiKey, fetchModels]);

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