
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Checkbox } from "@/components/ui/checkbox";
import { formatDetailsToYaml } from '../utils';
import type { DataSourcesConfig, DataSourceConfig, DataSourceProvider } from '@/types';

interface DataSourcesConfigTabProps {
  dsLoading: boolean;
  dsError: any;
  localDataSources: DataSourcesConfig;
  setLocalDataSources: React.Dispatch<React.SetStateAction<DataSourcesConfig>>;
  testResults: Record<string, { success: boolean; summary: string; details?: string } | null>;
  handleTestTushare: () => void;
  handleTestFinnhub: () => void;
  handleTestAlphaVantage: () => void;
}

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 DataSourcesConfigTab({
  dsLoading,
  dsError,
  localDataSources,
  setLocalDataSources,
  testResults,
  handleTestTushare,
  handleTestFinnhub,
  handleTestAlphaVantage,
}: DataSourcesConfigTabProps) {
  return (
    <Card>
      <CardHeader>
        <CardTitle>数据源配置</CardTitle>
        <CardDescription>外部数据源 API 设置</CardDescription>
      </CardHeader>
      <CardContent className="space-y-6">
        {dsLoading && <div className="text-sm text-muted-foreground">加载数据源配置...</div>}
        {dsError && <div className="text-sm text-red-600">数据源配置加载失败: {String(dsError)}</div>}
        {!dsLoading && !dsError && (
          <div className="space-y-6">
            {(['tushare','finnhub','alphavantage','yfinance'] as DataSourceProvider[]).map((providerKey) => {
              const item: DataSourceConfig = localDataSources[providerKey] || {
                provider: providerKey,
                api_key: '',
                api_url: '',
                enabled: false,
              };
              return (
                <div key={providerKey} className="space-y-3 p-4 border rounded-lg">
                  <div className="flex items-center justify-between">
                    <div>
                      <Label className="text-base font-medium capitalize">{providerKey}</Label>
                      <p className="text-sm text-muted-foreground">
                        {providerKey === 'tushare' && '中国市场数据源'}
                        {providerKey === 'finnhub' && '全球市场数据源'}
                        {providerKey === 'alphavantage' && '全球市场数据源（MCP桥接）'}
                        {providerKey === 'yfinance' && '雅虎财经数据源'}
                      </p>
                    </div>
                    <div className="flex items-center gap-2">
                      <Checkbox
                        id={`${providerKey}-enabled`}
                        checked={!!item.enabled}
                        onCheckedChange={(checked) => {
                          setLocalDataSources((prev) => ({
                            ...prev,
                            [providerKey]: { ...item, enabled: !!checked, provider: providerKey },
                          }));
                        }}
                      />
                      <label htmlFor={`${providerKey}-enabled`} className="text-sm">启用</label>
                    </div>
                  </div>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <Label htmlFor={`${providerKey}-api-key`}>API Key</Label>
                      <Input
                        id={`${providerKey}-api-key`}
                        type="password"
                        value={item.api_key ?? ''}
                        onChange={(e) => {
                          const v = e.target.value;
                          setLocalDataSources((prev) => ({
                            ...prev,
                            [providerKey]: { ...item, api_key: v, provider: providerKey },
                          }));
                        }}
                        placeholder="留空表示清空或保持（根据启用状态）"
                      />
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor={`${providerKey}-api-url`}>API URL</Label>
                      <Input
                        id={`${providerKey}-api-url`}
                        type="text"
                        value={item.api_url ?? ''}
                        onChange={(e) => {
                          const v = e.target.value;
                          setLocalDataSources((prev) => ({
                            ...prev,
                            [providerKey]: { ...item, api_url: v, provider: providerKey },
                          }));
                        }}
                        placeholder={defaultUrls[providerKey] ?? 'https://...'}
                        disabled={providerKey === 'yfinance'}
                      />
                    </div>
                  </div>
                  <div className="flex gap-2">
                    {providerKey === 'tushare' && (
                      <Button variant="outline" onClick={handleTestTushare}>测试 Tushare</Button>
                    )}
                    {providerKey === 'finnhub' && (
                      <Button variant="outline" onClick={handleTestFinnhub}>测试 Finnhub</Button>
                    )}
                    {providerKey === 'alphavantage' && (
                      <Button variant="outline" onClick={handleTestAlphaVantage}>测试 AlphaVantage</Button>
                    )}
                  </div>
                  {testResults[providerKey] ? (() => {
                    const r = testResults[providerKey]!;
                    if (r.success) {
                      return (
                        <div className="text-sm text-green-600">
                          {r.summary}
                        </div>
                      );
                    }
                    return (
                      <div className="text-sm text-red-600">
                        <div className="font-medium">测试失败</div>
                        {r.details ? (
                          <details className="mt-2">
                            <summary className="cursor-pointer text-red-700 underline">查看详细错误（YAML）</summary>
                            <pre className="mt-2 p-2 rounded bg-red-50 text-red-700 whitespace-pre-wrap break-words">
{formatDetailsToYaml(r.details)}
                            </pre>
                          </details>
                        ) : null}
                      </div>
                    );
                  })() : null}
                </div>
              );
            })}
          </div>
        )}
      </CardContent>
    </Card>
  );
}

