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

/**
 * Web & Search settings.
 *
 * Replaces the `web` tab of the legacy grab-bag `ToolsForm` and folds
 * the standalone `SearchFilterForm` in as a sub-section (Step 3
 * INVESTIGATE #3 follow-up). The config keys are unchanged:
 *
 *   tools.searxng_url
 *   tools.webfetch_timeout
 *   tools.websearch_timeout
 *   tools.webfetch_allowed_hosts
 *   search_filter.blocked_patterns
 *   search_filter.auto_block.*
 */
export function ToolsWebForm({ config, onChange }: SectionFormProps) {
  const tools = config.tools ?? {};
  const sf = config.searchFilter ?? {};
  const autoBlock = sf.autoBlock ?? {};

  const toggleAutoBlock = (key: string, value: boolean) => {
    onChange(`searchFilter.autoBlock.${key}`, value);
  };

  return (
    <div className="space-y-6">
      <h2 className="text-base font-semibold text-slate-800">Web & Search</h2>

      <section className="space-y-5">
        <h3 className="text-xs font-semibold uppercase tracking-wide text-slate-500">
          Web Fetch / Search
        </h3>
        <div>
          <FieldLabel>SearXNG URL</FieldLabel>
          <FieldInput value={tools.searxngUrl ?? ''} onChange={v => onChange('tools.searxngUrl', v)} />
          <HelpText>WebSearch のフォールバック用 SearXNG エンドポイント。</HelpText>
        </div>
        <div>
          <FieldLabel>WebFetch Timeout (秒)</FieldLabel>
          <FieldInput type="number" value={tools.webfetchTimeout ?? 30}
            onChange={v => onChange('tools.webfetchTimeout', Number(v))} />
        </div>
        <div>
          <FieldLabel>WebSearch Timeout (秒)</FieldLabel>
          <FieldInput type="number" value={tools.websearchTimeout ?? 15}
            onChange={v => onChange('tools.websearchTimeout', Number(v))} />
        </div>
        <div>
          <FieldLabel>SSRF Allowed Hosts</FieldLabel>
          <StringArrayEditor
            value={tools.webfetchAllowedHosts ?? []}
            onChange={v => onChange('tools.webfetchAllowedHosts', v)}
            placeholder="hostname or IP address" />
          <HelpText>SSRF 保護の例外ホスト名／IP アドレス。WebFetch・BrowseWeb のすべてに適用。</HelpText>
        </div>
      </section>

      <section className="space-y-4 pt-2 border-t border-hairline">
        <h3 className="text-xs font-semibold uppercase tracking-wide text-slate-500">
          Search Filter
        </h3>

        <div>
          <FieldLabel>Blocked Patterns (ブロックパターン)</FieldLabel>
          <StringArrayEditor
            value={sf.blockedPatterns ?? []}
            onChange={v => onChange('searchFilter.blockedPatterns', v)}
            placeholder="regex pattern"
          />
          <HelpText>WebSearch クエリからフィルタするパターン（正規表現）。</HelpText>
        </div>

        <div>
          <FieldLabel>Auto Block (自動ブロック)</FieldLabel>
          <div className="space-y-2 mt-1">
            {([
              ['privateIp', 'プライベートIP', autoBlock.privateIp],
              ['internalDomain', '内部ドメイン', autoBlock.internalDomain],
              ['email', 'メールアドレス', autoBlock.email],
              ['phone', '電話番号', autoBlock.phone],
            ] as const).map(([key, label, checked]) => (
              <label key={key} className="flex items-center gap-2 text-sm text-slate-700">
                <input
                  type="checkbox"
                  checked={checked ?? false}
                  onChange={e => toggleAutoBlock(key, e.target.checked)}
                  className="rounded border-slate-300"
                />
                {label}
              </label>
            ))}
          </div>
          <HelpText>検索クエリに含まれる機密情報を自動でブロック。</HelpText>
        </div>
      </section>
    </div>
  );
}
