import { useMemo } from "react";

interface SystemSettingsProps {
  settings: Record<string, any>;
  alpacaMode: string | null;
  onSave: (key: string, value: any) => Promise<void>;
  saveError: string | null;
}

const KNOWN_KEYS = new Set([
  "llm.model", "llm.temperature", "llm.maxDebateRounds",
  "trading.maxLossPercent", "trading.positionSizePercent",
  "trading.takeProfitPercent", "trading.stopLossPercent", "trading.riskMethod",
]);

export default function SystemSettings({ settings, alpacaMode, onSave, saveError }: SystemSettingsProps) {
  const rawSettings = useMemo(() =>
    Object.entries(settings)
      .filter(([key]) => !KNOWN_KEYS.has(key))
      .map(([key, value]) => ({
        key,
        value: typeof value === "string" ? value : JSON.stringify(value, null, 2),
      })),
    [settings]
  );

  const handleRawSave = async (key: string, newValue: string) => {
    try {
      const parsed = JSON.parse(newValue);
      await onSave(key, parsed);
    } catch {
      await onSave(key, newValue);
    }
  };

  return (
    <div className="space-y-6">
      <div>
        <h2 className="text-xl font-bold text-gray-900">System</h2>
        <p className="text-sm text-gray-600 mt-1">System configuration and environment info.</p>
      </div>

      {saveError && (
        <div className="bg-red-50 text-red-700 px-4 py-2 rounded-lg text-sm">{saveError}</div>
      )}

      <div className="space-y-4">
        <div className="bg-gray-50 rounded-lg p-4 border border-gray-200">
          <h3 className="text-sm font-medium text-gray-700 mb-2">Alpaca Trading API</h3>
          <div className="flex items-center gap-3">
            <span className="text-sm text-gray-600">Mode:</span>
            <span className={`px-3 py-1 rounded-full text-sm font-medium ${
              alpacaMode === "live" ? "bg-red-100 text-red-700" : "bg-green-100 text-green-700"
            }`}>
              {alpacaMode === "live" ? "Live Trading" : "Paper Trading"}
            </span>
          </div>
        </div>

        {rawSettings.length > 0 && (
          <div>
            <h3 className="text-sm font-medium text-gray-700 mb-3">Additional Settings</h3>
            <div className="space-y-3">
              {rawSettings.map((setting) => (
                <div key={setting.key} className="flex items-start gap-4">
                  <div className="font-mono text-sm text-gray-600 w-48 shrink-0 pt-2">{setting.key}</div>
                  <textarea
                    key={setting.key + setting.value}
                    className="flex-1 border border-gray-300 rounded-lg px-3 py-2 text-sm font-mono focus:ring-2 focus:ring-blue-500"
                    rows={2}
                    defaultValue={setting.value}
                    onBlur={(e) => {
                      if (e.target.value !== setting.value) {
                        handleRawSave(setting.key, e.target.value);
                      }
                    }}
                  />
                </div>
              ))}
            </div>
          </div>
        )}

        {rawSettings.length === 0 && (
          <p className="text-sm text-gray-500">No additional settings configured.</p>
        )}
      </div>
    </div>
  );
}
