import { useState, useEffect } from 'react';
import {
  useDataSourcesConfig as useDataSourcesConfigApi,
  updateDataSourcesConfig,
  testConfig
} from '@/hooks/useApi';
import { DataSourcesConfig, DataSourceProvider, DataSourceConfig } from '@/types';

const defaultUrls: Partial<Record<DataSourceProvider, string>> = {
    tushare: 'http://api.tushare.pro',
    finnhub: 'https://finnhub.io/api/v1',
    alphavantage: 'https://mcp.alphavantage.co/mcp',
};

export function useDataSourcesConfigLogic() {
    const { data: initialDataSources, error: dsError, isLoading: dsLoading, mutate: mutateDataSources } = useDataSourcesConfigApi();
    const [localDataSources, setLocalDataSources] = useState<DataSourcesConfig>({});
    const [saving, setSaving] = useState(false);
    const [saveMessage, setSaveMessage] = useState('');
    const [testResults, setTestResults] = useState<Record<string, { success: boolean; summary: string; details?: string } | null>>({});

    useEffect(() => {
        if (initialDataSources) {
            setLocalDataSources(initialDataSources);
        }
    }, [initialDataSources]);

    const handleSave = async () => {
        setSaving(true);
        setSaveMessage('保存中...');

        try {
            if (initialDataSources) {
                const finalDataSources = JSON.parse(JSON.stringify(localDataSources));
                for (const key in finalDataSources) {
                    const providerKey = key as DataSourceProvider;
                    const source = finalDataSources[providerKey];
                    if (source && (source.api_url === null || source.api_url.trim() === '') && defaultUrls[providerKey]) {
                        source.api_url = defaultUrls[providerKey];
                    }
                }

                await updateDataSourcesConfig(finalDataSources);
                await mutateDataSources(finalDataSources, false);
                setLocalDataSources(finalDataSources);
            }
            setSaveMessage('保存成功！');
        } catch (e: any) {
            setSaveMessage(`保存失败: ${e.message}`);
        } finally {
            setSaving(false);
            setTimeout(() => setSaveMessage(''), 5000);
        }
    };

    const handleReset = () => {
        if (initialDataSources) setLocalDataSources(initialDataSources);
        setTestResults({});
        setSaveMessage('');
    };

    const handleTest = async (type: string, data: any) => {
        try {
            const result = await testConfig(type, data);
            const success = !!result?.success;
            const summary = typeof result?.message === 'string' && result.message.trim().length > 0
                ? result.message
                : (success ? '测试成功' : '测试失败');
            setTestResults(prev => ({ ...prev, [type]: { success, summary } }));
        } catch (e: any) {
            const summary: string = (e && typeof e === 'object' && 'summary' in e) ? String(e.summary) : (e?.message || '未知错误');
            const details: string | undefined = (e && typeof e === 'object' && 'details' in e) ? (e.details ? String(e.details) : undefined) : undefined;
            setTestResults(prev => ({
                ...prev,
                [type]: { success: false, summary, details }
            }));
        }
    };

    return {
        localDataSources,
        setLocalDataSources,
        dsLoading,
        dsError,
        saving,
        saveMessage,
        testResults,
        handleSave,
        handleReset,
        handleTest,
        defaultUrls
    };
}

