import { useState, useEffect, useRef } from "react";

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

export default function TradingSettings({ settings, onSave, saveError }: TradingSettingsProps) {
  const [maxLossPercent, setMaxLossPercent] = useState(settings["trading.maxLossPercent"] ?? 2);
  const [positionSizePercent, setPositionSizePercent] = useState(settings["trading.positionSizePercent"] ?? 10);
  const [takeProfitPercent, setTakeProfitPercent] = useState(settings["trading.takeProfitPercent"] ?? 5);
  const [stopLossPercent, setStopLossPercent] = useState(settings["trading.stopLossPercent"] ?? 3);
  const [riskMethod, setRiskMethod] = useState(settings["trading.riskMethod"] ?? "percentage");

  const saveTimersRef = useRef<Map<string, ReturnType<typeof setTimeout>>>(new Map());

  useEffect(() => {
    setMaxLossPercent(settings["trading.maxLossPercent"] ?? 2);
    setPositionSizePercent(settings["trading.positionSizePercent"] ?? 10);
    setTakeProfitPercent(settings["trading.takeProfitPercent"] ?? 5);
    setStopLossPercent(settings["trading.stopLossPercent"] ?? 3);
    setRiskMethod(settings["trading.riskMethod"] ?? "percentage");
  }, [settings]);

  const debouncedSave = (key: string, value: any) => {
    if (saveTimersRef.current.has(key)) {
      clearTimeout(saveTimersRef.current.get(key)!);
    }
    const timer = setTimeout(() => {
      onSave(key, value);
      saveTimersRef.current.delete(key);
    }, 300);
    saveTimersRef.current.set(key, timer);
  };

  useEffect(() => {
    return () => {
      saveTimersRef.current.forEach((timer) => clearTimeout(timer));
    };
  }, []);

  const clamp = (value: number, min: number, max: number) => Math.min(Math.max(value, min), max);

  return (
    <div className="space-y-6">
      <div>
        <h2 className="text-xl font-bold text-gray-900">Trading Defaults</h2>
        <p className="text-sm text-gray-600 mt-1">Default risk management and position sizing parameters.</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>
          <label htmlFor="max-loss" className="block text-sm font-medium text-gray-700 mb-1">Max Loss %</label>
          <input
            id="max-loss"
            type="number"
            min="0.1"
            max="100"
            step="0.1"
            value={maxLossPercent}
            onChange={(e) => {
              const v = clamp(parseFloat(e.target.value) || 0.1, 0.1, 100);
              setMaxLossPercent(v);
              debouncedSave("trading.maxLossPercent", v);
            }}
            className="w-32 border border-gray-300 rounded-lg px-4 py-2.5 text-gray-900 focus:ring-2 focus:ring-blue-500"
          />
          <p className="text-xs text-gray-500 mt-1">Maximum portfolio percentage to risk on a single trade.</p>
        </div>

        <div>
          <label htmlFor="position-size" className="block text-sm font-medium text-gray-700 mb-1">Position Size %</label>
          <input
            id="position-size"
            type="number"
            min="1"
            max="100"
            step="1"
            value={positionSizePercent}
            onChange={(e) => {
              const v = clamp(parseInt(e.target.value) || 1, 1, 100);
              setPositionSizePercent(v);
              debouncedSave("trading.positionSizePercent", v);
            }}
            className="w-32 border border-gray-300 rounded-lg px-4 py-2.5 text-gray-900 focus:ring-2 focus:ring-blue-500"
          />
          <p className="text-xs text-gray-500 mt-1">Default position size as percentage of available cash.</p>
        </div>

        <div>
          <label htmlFor="take-profit" className="block text-sm font-medium text-gray-700 mb-1">Take Profit %</label>
          <input
            id="take-profit"
            type="number"
            min="0.1"
            max="100"
            step="0.1"
            value={takeProfitPercent}
            onChange={(e) => {
              const v = clamp(parseFloat(e.target.value) || 0.1, 0.1, 100);
              setTakeProfitPercent(v);
              debouncedSave("trading.takeProfitPercent", v);
            }}
            className="w-32 border border-gray-300 rounded-lg px-4 py-2.5 text-gray-900 focus:ring-2 focus:ring-blue-500"
          />
          <p className="text-xs text-gray-500 mt-1">Target profit percentage for auto take-profit orders.</p>
        </div>

        <div>
          <label htmlFor="stop-loss" className="block text-sm font-medium text-gray-700 mb-1">Stop Loss %</label>
          <input
            id="stop-loss"
            type="number"
            min="0.1"
            max="100"
            step="0.1"
            value={stopLossPercent}
            onChange={(e) => {
              const v = clamp(parseFloat(e.target.value) || 0.1, 0.1, 100);
              setStopLossPercent(v);
              debouncedSave("trading.stopLossPercent", v);
            }}
            className="w-32 border border-gray-300 rounded-lg px-4 py-2.5 text-gray-900 focus:ring-2 focus:ring-blue-500"
          />
          <p className="text-xs text-gray-500 mt-1">Stop loss percentage below entry price.</p>
        </div>

        <div>
          <label htmlFor="risk-method" className="block text-sm font-medium text-gray-700 mb-1">Risk Method</label>
          <select
            id="risk-method"
            value={riskMethod}
            onChange={(e) => {
              setRiskMethod(e.target.value);
              debouncedSave("trading.riskMethod", e.target.value);
            }}
            className="w-full border border-gray-300 rounded-lg px-4 py-2.5 text-gray-900 focus:ring-2 focus:ring-blue-500"
          >
            <option value="fixed">Fixed amount</option>
            <option value="percentage">Percentage of portfolio</option>
            <option value="atr">ATR-based (Average True Range)</option>
          </select>
        </div>
      </div>
    </div>
  );
}
