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

const TOOL_TABS = [
  { id: 'web', label: 'Web' },
  { id: 'vision', label: 'Vision / OCR' },
  { id: 'x', label: 'X / Twitter' },
  { id: 'maps', label: 'Maps' },
  { id: 'amazon', label: 'Amazon' },
  { id: 'speech', label: 'Speech' },
  { id: 'knowledge', label: 'Knowledge (DKS) [LEGACY]' },
  { id: 'office', label: 'Office' },
  { id: 'uploads', label: 'Uploads' },
  { id: 'user-folder', label: 'User Folder' },
] as const;

export type ToolTabId = (typeof TOOL_TABS)[number]['id'];

interface ToolsFormProps extends SectionFormProps {
  /**
   * Restrict the visible set of sub-tabs. When omitted, all tabs are shown.
   * Used by the Settings sidebar Step 3 restructure to route sub-section ids
   * (tools-web / tools-browser / tools-media / tools-external /
   * tools-legacy-knowledge) into the same ToolsForm with a narrowed scope.
   */
  visibleTabs?: readonly ToolTabId[];
}

export function ToolsForm({ config, onChange, visibleTabs }: ToolsFormProps) {
  const { t } = useTranslation('settings');
  const tools = config.tools ?? {};
  const tabsToShow = visibleTabs && visibleTabs.length > 0
    ? TOOL_TABS.filter(t => visibleTabs.includes(t.id))
    : TOOL_TABS;
  const [tab, setTab] = useState<ToolTabId>(tabsToShow[0]?.id ?? 'web');

  // When visibleTabs changes (sidebar section change), reset to first tab
  // of the new scope so we don't render a hidden tab's content.
  useEffect(() => {
    if (!tabsToShow.some(t => t.id === tab)) {
      setTab(tabsToShow[0]?.id ?? 'web');
    }
  }, [tabsToShow, tab]);

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

      <nav className="flex flex-wrap gap-1 border-b border-hairline -mt-2" aria-label={t('tools.categoriesAria')}>
        {tabsToShow.map(t => (
          <button
            key={t.id}
            type="button"
            onClick={() => setTab(t.id)}
            aria-current={tab === t.id ? 'page' : undefined}
            className={`px-3 py-1.5 text-xs border-b-2 -mb-px transition-colors ${
              tab === t.id
                ? 'border-accent font-semibold text-accent'
                : 'border-transparent text-slate-500 hover:text-slate-800'
            }`}
          >
            {t.label}
          </button>
        ))}
      </nav>

      {tab === 'web' && (
        <div className="space-y-5">
          <div>
            <FieldLabel>SearXNG URL</FieldLabel>
            <FieldInput value={tools.searxngUrl ?? ''} onChange={v => onChange('tools.searxngUrl', v)} />
            <HelpText>{t('tools.web.searxngHelp')}</HelpText>
          </div>
          <div>
            <FieldLabel>{t('tools.web.webfetchTimeout')}</FieldLabel>
            <FieldInput type="number" value={tools.webfetchTimeout ?? 30}
              onChange={v => onChange('tools.webfetchTimeout', Number(v))} />
          </div>
          <div>
            <FieldLabel>{t('tools.web.websearchTimeout')}</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>{t('tools.web.ssrfHelp')}</HelpText>
          </div>
        </div>
      )}

      {tab === 'vision' && (
        <div className="space-y-5">
          <div>
            <FieldLabel>Vision Model</FieldLabel>
            <FieldInput value={tools.visionModel ?? ''} onChange={v => onChange('tools.visionModel', v)} />
            <HelpText>{t('tools.vision.modelHelp')}</HelpText>
          </div>
          <div>
            <FieldLabel>Vision Base URL</FieldLabel>
            <FieldInput value={tools.visionBaseUrl ?? ''} onChange={v => onChange('tools.visionBaseUrl', v)}
              placeholder={t('tools.vision.baseUrlPlaceholder')} />
            <HelpText>{t('tools.vision.baseUrlHelp')}</HelpText>
          </div>
          <div>
            <FieldLabel>{t('tools.vision.timeout')}</FieldLabel>
            <FieldInput type="number" value={tools.visionTimeout ?? 60}
              onChange={v => onChange('tools.visionTimeout', Number(v))} />
          </div>
          <div>
            <FieldLabel>Vision Max Tokens</FieldLabel>
            <FieldInput type="number" value={tools.visionMaxTokens ?? 1024}
              onChange={v => onChange('tools.visionMaxTokens', Number(v))} />
          </div>
          <div>
            <FieldLabel>OCR Model</FieldLabel>
            <FieldInput value={tools.ocrModel ?? ''} onChange={v => onChange('tools.ocrModel', v)}
              placeholder="glm-ocr" />
            <HelpText>{t('tools.vision.ocrModelHelp')}</HelpText>
          </div>
        </div>
      )}

      {tab === 'x' && (
        <div className="space-y-5">
          <div>
            <FieldLabel>X Auth Token</FieldLabel>
            <FieldInput type="password" value={tools.xAuthToken ?? ''} onChange={v => onChange('tools.xAuthToken', v)} />
            <HelpText>{t('tools.x.authTokenHelp')}</HelpText>
          </div>
          <div>
            <FieldLabel>X ct0</FieldLabel>
            <FieldInput type="password" value={tools.xCt0 ?? ''} onChange={v => onChange('tools.xCt0', v)} />
            <HelpText>{t('tools.x.ct0Help')}</HelpText>
          </div>
          <div>
            <FieldLabel>X CLI Command</FieldLabel>
            <FieldInput value={Array.isArray(tools.xCliCommand) ? tools.xCliCommand.join(' ') : (tools.xCliCommand ?? '')}
              onChange={v => onChange('tools.xCliCommand', v)} />
            <HelpText>{t('tools.x.cliHelp')}</HelpText>
          </div>
          <div>
            <FieldLabel>{t('tools.x.timeout')}</FieldLabel>
            <FieldInput type="number" value={tools.xTimeout ?? 90}
              onChange={v => onChange('tools.xTimeout', Number(v))} />
          </div>
          <div>
            <FieldLabel>X Proxy</FieldLabel>
            <FieldInput value={tools.xProxy ?? ''} onChange={v => onChange('tools.xProxy', v)}
              placeholder="http://proxy:port" />
          </div>
          <div>
            <FieldLabel>X Chrome Profile</FieldLabel>
            <FieldInput value={tools.xChromeProfile ?? ''} onChange={v => onChange('tools.xChromeProfile', v)}
              placeholder="/path/to/chrome/profile" />
            <HelpText>{t('tools.x.chromeProfileHelp')}</HelpText>
          </div>
        </div>
      )}

      {tab === 'maps' && (
        <div className="space-y-5">
          <div>
            <FieldLabel>Google Maps API Key</FieldLabel>
            <FieldInput type="password" value={tools.googleMapsApiKey ?? ''} onChange={v => onChange('tools.googleMapsApiKey', v)} />
            <HelpText>{t('tools.maps.keyHelp')}</HelpText>
          </div>
        </div>
      )}

      {tab === 'amazon' && (
        <div className="space-y-5">
          <div>
            <FieldLabel>Amazon Affiliate Tag</FieldLabel>
            <FieldInput value={tools.amazonAffiliateTag ?? ''} onChange={v => onChange('tools.amazonAffiliateTag', v)}
              placeholder="your-tag-22" />
            <HelpText>{t('tools.amazon.affiliateHelp')}</HelpText>
          </div>
          <div>
            <FieldLabel>Keepa API Key</FieldLabel>
            <FieldInput type="password" value={tools.keepaApiKey ?? ''} onChange={v => onChange('tools.keepaApiKey', v)} />
            <HelpText>{t('tools.amazon.keepaHelp')}</HelpText>
          </div>
        </div>
      )}

      {tab === 'speech' && (
        <div className="space-y-5">
          <div>
            <FieldLabel>Speech Server URL</FieldLabel>
            <FieldInput value={tools.speechServerUrl ?? ''} onChange={v => onChange('tools.speechServerUrl', v)}
              placeholder="http://localhost:8000/v1" />
            <HelpText>{t('tools.speech.serverHelp')}</HelpText>
          </div>
          <div>
            <FieldLabel>{t('tools.speech.timeout')}</FieldLabel>
            <FieldInput type="number" value={tools.speechTimeout ?? 300}
              onChange={v => onChange('tools.speechTimeout', Number(v))} />
            <HelpText>{t('tools.speech.timeoutHelp')}</HelpText>
          </div>
          <div>
            <FieldLabel>Speech Language</FieldLabel>
            <FieldInput value={tools.speechLanguage ?? 'ja'} onChange={v => onChange('tools.speechLanguage', v)}
              placeholder="ja" />
            <HelpText>{t('tools.speech.languageHelp')}</HelpText>
          </div>
        </div>
      )}

      {tab === 'knowledge' && (
        <div className="space-y-5">
          <div className="flex items-center gap-2">
            <h3 className="text-sm font-semibold text-slate-800">Knowledge (DKS)</h3>
            <span
              className="inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-semibold uppercase tracking-wide bg-amber-100 dark:bg-amber-500/15 text-amber-800 dark:text-amber-300 border border-amber-300 dark:border-amber-500/30"
              title={t('tools.knowledge.legacyBadgeTitle')}
            >
              LEGACY
            </span>
          </div>
          <div
            role="note"
            className="rounded border border-amber-300 dark:border-amber-500/30 bg-amber-50 dark:bg-amber-500/15 px-3 py-2 text-xs text-amber-900 dark:text-amber-300"
          >
            {t('tools.knowledge.note')}{' '}
            <a
              href="/help"
              className="underline text-amber-900 dark:text-amber-300 hover:text-amber-700 dark:hover:text-amber-300"
              target="_blank"
              rel="noopener noreferrer"
            >
              {t('tools.knowledge.mcpGuideLink')}
            </a>
          </div>
          <div>
            <FieldLabel>Knowledge Service URL</FieldLabel>
            <FieldInput value={tools.knowledgeServiceUrl ?? ''} onChange={v => onChange('tools.knowledgeServiceUrl', v)}
              placeholder="http://dks-server:8100" />
            <HelpText>{t('tools.knowledge.serviceUrlHelp')}</HelpText>
          </div>
          <div>
            <FieldLabel>Knowledge Namespaces</FieldLabel>
            <NamespaceEditor
              value={tools.knowledgeNamespaces ?? {}}
              onChange={v => onChange('tools.knowledgeNamespaces', v)}
              addDisabled
              addDisabledReason={t('tools.knowledge.addDisabledReason')}
              addDisabledHref="/help"
            />
            <HelpText>{t('tools.knowledge.namespacesHelp')}</HelpText>
          </div>
        </div>
      )}

      {tab === 'user-folder' && (
        <div className="space-y-5">
          <div>
            <FieldLabel>{t('tools.userScripts.enableLabel')}</FieldLabel>
            <label className="inline-flex items-center gap-2 text-[13px] text-slate-700">
              <input
                type="checkbox"
                checked={tools.userScriptsEnabled === true}
                onChange={e => onChange('tools.userScriptsEnabled', e.target.checked)}
              />
              <span>{t('tools.userScripts.enabledToggle')}</span>
            </label>
            <HelpText>{t('tools.userScripts.enableHelp')}</HelpText>
          </div>
          <div>
            <FieldLabel>{t('tools.userScripts.allowlistLabel')}</FieldLabel>
            <StringArrayEditor
              value={tools.userScriptsAllowUserids ?? []}
              onChange={v => onChange('tools.userScriptsAllowUserids', v)}
              placeholder={t('tools.userScripts.allowlistPlaceholder')}
            />
            <HelpText>{t('tools.userScripts.allowlistHelp')}</HelpText>
          </div>
          <div>
            <FieldLabel>{t('tools.userScripts.trashRetentionLabel')}</FieldLabel>
            <FieldInput type="number" value={tools.trashRetentionDays ?? 30}
              onChange={v => onChange('tools.trashRetentionDays', Number(v))} />
            <HelpText>{t('tools.userScripts.trashRetentionHelp')}</HelpText>
          </div>
        </div>
      )}

      {tab === 'uploads' && (
        <div className="space-y-5">
          <HelpText>{t('tools.uploads.sectionHelp')}</HelpText>
          <div>
            <FieldLabel>{t('tools.uploads.maxLabel')}</FieldLabel>
            <FieldInput type="number" value={tools.taskUploadMaxSizeMb ?? 50}
              onChange={v => onChange('tools.taskUploadMaxSizeMb', Number(v))} />
            <HelpText>{t('tools.uploads.maxHelp')}</HelpText>
          </div>
        </div>
      )}

      {tab === 'office' && (
        <div className="space-y-5">
          <HelpText>{t('tools.office.sectionHelp')}</HelpText>
          <div>
            <FieldLabel>{t('tools.office.excelLabel')}</FieldLabel>
            <FieldInput type="number" value={tools.officeExcelMaxSizeMb ?? 10}
              onChange={v => onChange('tools.officeExcelMaxSizeMb', Number(v))} />
            <HelpText>{t('tools.office.excelHelp')}</HelpText>
          </div>
          <div>
            <FieldLabel>{t('tools.office.docxLabel')}</FieldLabel>
            <FieldInput type="number" value={tools.officeDocxMaxSizeMb ?? 10}
              onChange={v => onChange('tools.officeDocxMaxSizeMb', Number(v))} />
            <HelpText>{t('tools.office.docxHelp')}</HelpText>
          </div>
          <div>
            <FieldLabel>{t('tools.office.pdfLabel')}</FieldLabel>
            <FieldInput type="number" value={tools.officePdfMaxSizeMb ?? 10}
              onChange={v => onChange('tools.officePdfMaxSizeMb', Number(v))} />
            <HelpText>{t('tools.office.pdfHelp')}</HelpText>
          </div>
          <div>
            <FieldLabel>{t('tools.office.pptxLabel')}</FieldLabel>
            <FieldInput type="number" value={tools.officePptxMaxSizeMb ?? 50}
              onChange={v => onChange('tools.officePptxMaxSizeMb', Number(v))} />
            <HelpText>{t('tools.office.pptxHelp')}</HelpText>
          </div>
          <div>
            <FieldLabel>{t('tools.office.pptxUncompressedLabel')}</FieldLabel>
            <FieldInput type="number" value={tools.officePptxMaxUncompressedMb ?? 200}
              onChange={v => onChange('tools.officePptxMaxUncompressedMb', Number(v))} />
            <HelpText>{t('tools.office.pptxUncompressedHelp')}</HelpText>
          </div>
        </div>
      )}
    </div>
  );
}
