import { useState } from 'react';
import { useConfigStore } from '@/stores/useConfigStore';

export function useSystemConfig() {
  const { config } = useConfigStore();
  const [saveMessage, setSaveMessage] = useState('');

  const handleExportConfig = () => {
    if (!config) return;
    
    const configToExport = {
      new_api: config.new_api,
      data_sources: config.data_sources,
      export_time: new Date().toISOString(),
      version: "1.0"
    };
    
    const blob = new Blob([JSON.stringify(configToExport, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `config-backup-${new Date().toISOString().split('T')[0]}.json`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  };

  const handleImportConfig = (event: React.ChangeEvent<HTMLInputElement>, onImportSuccess?: (config: any) => void) => {
    const file = event.target.files?.[0];
    if (!file) return;

    const reader = new FileReader();
    reader.onload = (e) => {
      try {
        const importedConfig = JSON.parse(e.target?.result as string);
        
        if (onImportSuccess) {
            onImportSuccess(importedConfig);
        }
        
        setSaveMessage('配置导入成功，请检查并保存');
      } catch (error) {
        setSaveMessage('配置文件格式错误，导入失败');
      }
    };
    reader.readAsText(file);
  };

  return {
    config,
    saveMessage,
    handleExportConfig,
    handleImportConfig
  };
}

