import { HelpText } from './HelpText';
import { FieldLabel, FieldInput } from './formUtils';
import type { SectionFormProps } from './types';

export function ContextForm({ config, onChange }: SectionFormProps) {
  const ctx = config.context ?? {};
  const thresholds = ctx.thresholds ?? [
    { ratio: 0.7, action: 'warn' },
    { ratio: 0.85, action: 'prompt' },
    { ratio: 0.95, action: 'force_transition' },
  ];

  const updateThreshold = (index: number, field: string, value: string | number) => {
    const updated = thresholds.map((t: { ratio: number; action: string }, i: number) =>
      i === index ? { ...t, [field]: field === 'ratio' ? Number(value) : value } : t
    );
    onChange('context.thresholds', updated);
  };

  return (
    <div className="space-y-5">
      <h2 className="text-base font-semibold text-slate-800">Context</h2>

      <div>
        <FieldLabel>Limit Tokens</FieldLabel>
        <FieldInput type="number" value={ctx.limitTokens ?? ''}
          onChange={v => onChange('context.limitTokens', v ? Number(v) : undefined)}
          placeholder="auto (Ollama API から取得)" />
        <HelpText>トークン上限の手動指定。空欄で自動取得。</HelpText>
      </div>

      <div>
        <FieldLabel>Thresholds (閾値)</FieldLabel>
        <div className="space-y-2 mt-1">
          {thresholds.map((t: { ratio: number; action: string }, i: number) => (
            <div key={i} className="flex gap-2 items-center">
              <input type="number" step="0.01" min="0" max="1"
                value={t.ratio}
                onChange={e => updateThreshold(i, 'ratio', e.target.value)}
                className="w-20 px-2 py-1 text-sm border border-slate-300 rounded" />
              <select value={t.action}
                onChange={e => updateThreshold(i, 'action', e.target.value)}
                className="px-2 py-1 text-sm border border-slate-300 rounded">
                <option value="warn">warn</option>
                <option value="prompt">prompt</option>
                <option value="force_transition">force_transition</option>
              </select>
            </div>
          ))}
        </div>
        <HelpText>
          コンテキスト使用率に応じたアクション。ratio は 0〜1。
          warn: ログに警告を出力するのみ ／ prompt: LLM へ遷移を促すメッセージを注入 ／ force_transition: default_next に強制遷移
        </HelpText>
      </div>
    </div>
  );
}
