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

export function ContextForm({ config, onChange }: SectionFormProps) {
  const { t } = useTranslation('settings');
  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((th: { ratio: number; action: string }, i: number) =>
      i === index ? { ...th, [field]: field === 'ratio' ? Number(value) : value } : th
    );
    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={t('context.limitPlaceholder')} />
        <HelpText>{t('context.limitHelp')}</HelpText>
      </div>

      <div>
        <FieldLabel>{t('context.thresholdsLabel')}</FieldLabel>
        <div className="space-y-2 mt-1">
          {thresholds.map((th: { 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={th.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={th.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>
          {t('context.thresholdsHelp')}
        </HelpText>
      </div>
    </div>
  );
}
