"use client";
import { useState } from 'react';
import { useDashboard } from '../dashboard-context';
import SecretsTab from './secrets-tab.jsx';
import AllowlistsTab from './allowlists-tab.jsx';
import EnvTab from './env-tab.jsx';

const TOOLS_SUBTABS = [
  ['connectors', 'Connectors', 'Trust + tool toggles'],
  ['secrets', 'Secrets', 'Encrypted vault'],
  ['allowlists', 'Allowlists', 'Destination scope'],
  ['local-config', 'Local config', 'Non-credential env'],
];

export default function ToolsTab() {
  const {
    configTools,
    toggleTool,
    trustMode,
    trustModeBusy,
    toggleTrustMode,
  } = useDashboard();
  const [toolsSub, setToolsSub] = useState('connectors');
  const isTrusted = trustMode === 'auto';
  return (
    <div className="config-body">
      <div className="config-page-head">
        <span>Tools</span>
        <p>Enable connectors, manage credentials, and scope external destinations. One pane at a time — pick a section.</p>
      </div>

      <nav className="tools-subnav" role="tablist" aria-label="Tools sections">
        {TOOLS_SUBTABS.map(([id, label, desc]) => (
          <button
            key={id}
            type="button"
            role="tab"
            aria-selected={toolsSub === id}
            className={'tools-subnav-pill' + (toolsSub === id ? ' on' : '')}
            onClick={() => setToolsSub(id)}
          >
            <b>{label}</b>
            <small>{desc}</small>
          </button>
        ))}
      </nav>

      {toolsSub === 'connectors' && (
        <div className="tools-pane">
          <div className={'trust-mode-card' + (isTrusted ? ' on' : '')}>
            <div className="trust-mode-info">
              <div className="trust-mode-titleline">
                <span className="trust-mode-name">Main agent trust mode</span>
                <span className={'trust-mode-pill ' + (isTrusted ? 'on' : 'off')}>
                  {isTrusted ? 'Trusted' : 'Approval required'}
                </span>
              </div>
              <p className="trust-mode-desc">
                {isTrusted
                  ? 'High-risk tool calls run immediately. Irreversible external tools always require approval regardless of this setting. Destructive commands (sudo, rm -rf, git reset --hard) remain blocked.'
                  : 'High-risk tool calls (file writes, terminal, processes) create an approval request before running. Irreversible external tools always require approval regardless of this setting.'}
              </p>
            </div>
            <button
              type="button"
              className={'config-tool-toggle' + (isTrusted ? ' on' : '')}
              onClick={() => !trustModeBusy && toggleTrustMode && toggleTrustMode()}
              disabled={trustModeBusy}
              aria-label={isTrusted ? 'Disable trust mode' : 'Enable trust mode'}
              aria-pressed={isTrusted}
            >
              <span />
            </button>
          </div>

          <div className="config-tools-panel">
            <div className="config-section-title">Available tools</div>
            {[...new Set(configTools.map(tool => tool.category))].map(category => (
              <section className="config-tool-group" key={category}>
                <div className="config-tool-group-head">{category}</div>
                <div className="config-tools-list">
                  {configTools.filter(tool => tool.category === category).map(tool => (
                    <div key={tool.name} className={'config-tool-row' + (tool.enabled ? ' on' : '')}>
                      <div className="config-tool-main">
                        <div>
                          <div className="config-tool-titleline">
                            <span className="config-tool-name">{tool.title || tool.name.replace(/_/g, ' ')}</span>
                            {tool.risk_level === 'irreversible_external' ? (
                              <span
                                className="config-tool-risk irreversible"
                                title="Always requires approval, regardless of trust mode."
                              >
                                irreversible
                              </span>
                            ) : (
                              <span className={'config-tool-risk ' + (tool.risk_level || 'low')}>{tool.risk_level || 'low'}</span>
                            )}
                          </div>
                          <p className="config-tool-desc">{tool.description}</p>
                          <div className="config-tool-status">
                            <span className={tool.available ? 'ready' : 'missing'}>
                              {tool.available ? 'Ready' : `Missing ${tool.missing_env?.join(', ') || 'configuration'}`}
                            </span>
                            {tool.risk_level === 'irreversible_external' && (
                              <span className="config-tool-irreversible-notice">Always requires approval</span>
                            )}
                            {tool.approval_required && tool.risk_level !== 'irreversible_external' && <span>Approval required</span>}
                          </div>
                        </div>
                        <button
                          type="button"
                          className={'config-tool-toggle' + (tool.enabled ? ' on' : '')}
                          onClick={() => toggleTool(tool, !tool.enabled)}
                          aria-label={`${tool.enabled ? 'Disable' : 'Enable'} ${tool.title || tool.name}`}
                          aria-pressed={tool.enabled}
                        >
                          <span />
                        </button>
                      </div>
                    </div>
                  ))}
                </div>
              </section>
            ))}
          </div>
        </div>
      )}

      {toolsSub === 'secrets' && (
        <div className="tools-pane">
          <SecretsTab />
        </div>
      )}

      {toolsSub === 'allowlists' && (
        <div className="tools-pane">
          <AllowlistsTab />
        </div>
      )}

      {toolsSub === 'local-config' && <EnvTab />}
    </div>
  );
}
