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

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

const DEFAULT_MODEL = "openai/gpt-oss-120b:free";
const DEFAULT_TEMPERATURE = 0.7;
const DEFAULT_MAX_DEBATE_ROUNDS = 3;

const AVAILABLE_MODELS = [
  "openai/gpt-oss-120b:free",
  "openrouter/free",
  "deepseek/deepseek-chat:free",
  "meta/llama-3.3-70b-instruct:free",
];

export default function LlmSettings({ settings, onSave, saveError }: LlmSettingsProps) {
  const [model, setModel] = useState(settings["llm.model"] ?? DEFAULT_MODEL);
  const [temperature, setTemperature] = useState(settings["llm.temperature"] ?? DEFAULT_TEMPERATURE);
  const [maxDebateRounds, setMaxDebateRounds] = useState(settings["llm.maxDebateRounds"] ?? DEFAULT_MAX_DEBATE_ROUNDS);
  const tempTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  useEffect(() => {
    setModel(settings["llm.model"] ?? DEFAULT_MODEL);
    setTemperature(settings["llm.temperature"] ?? DEFAULT_TEMPERATURE);
    setMaxDebateRounds(settings["llm.maxDebateRounds"] ?? DEFAULT_MAX_DEBATE_ROUNDS);
    return () => {
      if (tempTimerRef.current) clearTimeout(tempTimerRef.current);
    };
  }, [settings]);

  const saveModel = async (value: string) => {
    setModel(value);
    await onSave("llm.model", value);
  };

  const saveTemperature = async (value: number) => {
    setTemperature(value);
    if (tempTimerRef.current) clearTimeout(tempTimerRef.current);
    tempTimerRef.current = setTimeout(() => {
      onSave("llm.temperature", value).catch((e) => console.error("Failed to save temperature:", e));
    }, 300);
  };

  const saveMaxDebateRounds = async (value: number) => {
    const clamped = Math.min(10, Math.max(1, value));
    setMaxDebateRounds(clamped);
    await onSave("llm.maxDebateRounds", clamped);
  };

  return (
    <div className="space-y-6">
      <div>
        <h2 className="text-xl font-bold text-gray-900">LLM & Agents</h2>
        <p className="text-sm text-gray-600 mt-1">Configure the language model and agent behavior for trading analysis.</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="llm-model" className="block text-sm font-medium text-gray-700 mb-1">Model</label>
          <select
            id="llm-model"
            value={model}
            onChange={(e) => saveModel(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 focus:border-blue-500"
          >
            {AVAILABLE_MODELS.map((m) => (
              <option key={m} value={m}>{m}</option>
            ))}
          </select>
        </div>

        <div>
          <label htmlFor="llm-temperature" className="block text-sm font-medium text-gray-700 mb-1">
            Temperature: {temperature.toFixed(1)}
          </label>
          <input
            id="llm-temperature"
            type="range"
            min="0"
            max="2"
            step="0.1"
            value={temperature}
            onChange={(e) => saveTemperature(parseFloat(e.target.value))}
            className="w-full"
          />
          <div className="flex justify-between text-xs text-gray-500">
            <span>0.0 (deterministic)</span>
            <span>2.0 (creative)</span>
          </div>
        </div>

        <div>
          <label htmlFor="llm-max-debate-rounds" className="block text-sm font-medium text-gray-700 mb-1">Max Debate Rounds</label>
          <input
            id="llm-max-debate-rounds"
            type="number"
            min="1"
            max="10"
            value={maxDebateRounds}
            onChange={(e) => saveMaxDebateRounds(Math.max(1, parseInt(e.target.value) || 1))}
            className="w-32 border border-gray-300 rounded-lg px-4 py-2.5 text-gray-900 focus:ring-2 focus:ring-blue-500"
          />
        </div>
      </div>
    </div>
  );
}
