
import { useState } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Label } from "@/components/ui/label";
import type { SystemConfig } from '@/stores/useConfigStore';

interface SystemConfigTabProps {
  config: SystemConfig | null;
  setSaveMessage: (msg: string) => void;
  setNewProviderBaseUrl: (url: string) => void;
}

export function SystemConfigTab({ config, setSaveMessage, setNewProviderBaseUrl }: SystemConfigTabProps) {

  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>) => {
    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 (importedConfig.new_api?.base_url) {
          setNewProviderBaseUrl(importedConfig.new_api.base_url);
        }
        
        setSaveMessage('配置导入成功，请检查并保存');
      } catch (error) {
        setSaveMessage('配置文件格式错误，导入失败');
      }
    };
    reader.readAsText(file);
  };

  return (
    <div className="space-y-4">
      <Card>
        <CardHeader>
          <CardTitle>系统信息</CardTitle>
          <CardDescription>当前系统状态和配置概览</CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label>New API</Label>
              <Badge variant={config?.new_api?.api_key ? 'default' : 'secondary'}>
                {config?.new_api?.api_key ? '已配置' : '未配置'}
              </Badge>
            </div>
            <div className="space-y-2">
              <Label>Tushare API</Label>
              <Badge variant={config?.data_sources?.tushare?.api_key ? 'default' : 'secondary'}>
                {config?.data_sources?.tushare?.api_key ? '已配置' : '未配置'}
              </Badge>
            </div>
            <div className="space-y-2">
              <Label>Finnhub API</Label>
              <Badge variant={config?.data_sources?.finnhub?.api_key ? 'default' : 'secondary'}>
                {config?.data_sources?.finnhub?.api_key ? '已配置' : '未配置'}
              </Badge>
            </div>
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>配置管理</CardTitle>
          <CardDescription>导入、导出和备份配置</CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="flex flex-col sm:flex-row gap-4">
            <Button onClick={handleExportConfig} variant="outline" className="flex-1">
              📤 导出配置
            </Button>
            <div className="flex-1">
              <input
                type="file"
                accept=".json"
                onChange={handleImportConfig}
                className="hidden"
                id="import-config"
              />
              <Button 
                variant="outline" 
                className="w-full"
                onClick={() => document.getElementById('import-config')?.click()}
              >
                📥 导入配置
              </Button>
            </div>
          </div>
          <div className="text-sm text-muted-foreground">
            <p>• 导出配置将下载当前所有配置的备份文件</p>
            <p>• 导入配置将加载备份文件中的设置（不包含敏感信息）</p>
            <p>• 建议定期备份配置以防数据丢失</p>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}

