import { useState } from 'react';
import { GoaOrchestratorPanel } from '@/features/goa/GoaOrchestratorPanel';
import { formatServiceResult, hyperloopPreflight, hyperloopProcess, templateMatch } from '@/lib/vigthoria-services';
import { renderMarkdownHtml } from '@/lib/markdown';
import { ReportPanel } from '@/features/agent/ReportPanel';
import { useActiveWorkspace, useWorkbenchStore } from '@/features/workspace/WorkspaceStore';
import { CODER_UPGRADE_URL, hasAnyCoderPlan, hasHyperTierPlan } from '@/lib/plan-gate';
import type { ToolsTabId } from '@/types/workbench';

const TABS: { id: ToolsTabId; label: string }[] = [
  { id: 'report', label: 'Report' },
  { id: 'goa', label: 'GOA' },
  { id: 'hyperloop', label: 'Hyper-Loop' },
  { id: 'templates', label: 'Templates' },
];

export function ServicesPanel() {
  const settings = useWorkbenchStore((s) => s.settings);
  const auth = useWorkbenchStore((s) => s.auth);
  const toolsTab = useWorkbenchStore((s) => s.toolsTab);
  const setToolsTab = useWorkbenchStore((s) => s.setToolsTab);
  const serviceResult = useWorkbenchStore((s) => s.serviceResult);
  const setServiceResult = useWorkbenchStore((s) => s.setServiceResult);
  const workspace = useActiveWorkspace();

  const [prompt, setPrompt] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const runHyperloop = async (mode: 'preflight' | 'process') => {
    if (!auth.authenticated || !auth.hasToken) {
      setError('Login required. Run vigthoria login in the Main Agent terminal.');
      return;
    }
    if (!hasHyperTierPlan(auth)) {
      setError('Hyper-Loop requires an active Pro, Professional, Enterprise, or Master Admin Vigthoria Coder subscription. Upgrade at ' + CODER_UPGRADE_URL);
      return;
    }
    const token = await useWorkbenchStore.getState().getAuthToken();
    if (!token) {
      setError('No auth token in CLI config.');
      return;
    }
    setLoading(true);
    setError(null);
    try {
      const fn = mode === 'preflight' ? hyperloopPreflight : hyperloopProcess;
      const data = await fn(
        settings.hyperloopUrl || 'https://hyperloop.vigthoria.io',
        token,
        prompt,
        workspace?.rootPath,
      );
      setServiceResult(formatServiceResult(data));
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : String(err));
    } finally {
      setLoading(false);
    }
  };

  const runTemplate = async () => {
    if (!hasAnyCoderPlan(auth)) {
      setError('Templates requires an active Vigthoria Coder subscription. Upgrade at ' + CODER_UPGRADE_URL);
      return;
    }
    const token = auth.hasToken ? await useWorkbenchStore.getState().getAuthToken() : null;
    setLoading(true);
    setError(null);
    try {
      const data = await templateMatch(
        settings.templateUrl || 'https://templates.vigthoria.io',
        token ?? '',
        prompt,
      );
      setServiceResult(formatServiceResult(data));
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : String(err));
    } finally {
      setLoading(false);
    }
  };

  return (
    <aside className="services-panel">
      <div className="services-panel__tabs">
        {TABS.map((tab) => (
          <button
            key={tab.id}
            type="button"
            className={`services-panel__tab ${toolsTab === tab.id ? 'is-active' : ''}`}
            onClick={() => void setToolsTab(tab.id)}
          >
            {tab.label}
          </button>
        ))}
      </div>

      {toolsTab === 'report' && <ReportPanel />}

      {toolsTab === 'goa' && <GoaOrchestratorPanel />}

      {toolsTab === 'hyperloop' && (
        <div className="services-panel__body">
          <p className="services-panel__intro">
            Routed code analysis via Hyper-Loop (authenticated API). Use for architecture reviews, refactors, and module routing.
          </p>
          <textarea
            className="services-panel__input"
            rows={4}
            placeholder="e.g. Analyze src/ for dependency issues and suggest refactor plan"
            value={prompt}
            onChange={(e) => setPrompt(e.target.value)}
          />
          <div className="services-panel__actions">
            <button type="button" disabled={loading || !prompt.trim()} onClick={() => void runHyperloop('preflight')}>
              Preflight
            </button>
            <button type="button" className="is-primary" disabled={loading || !prompt.trim()} onClick={() => void runHyperloop('process')}>
              {loading ? 'Running…' : 'Run Hyper-Loop'}
            </button>
          </div>
          {error && <p className="services-panel__error">{error}</p>}
          {serviceResult && (
            <div
              className="services-panel__result markdown-body"
              dangerouslySetInnerHTML={{ __html: renderMarkdownHtml(serviceResult) }}
            />
          )}
        </div>
      )}

      {toolsTab === 'templates' && (
        <div className="services-panel__body">
          <p className="services-panel__intro">
            Match a vision to HTML templates (Template Service). Best for landing pages, dashboards, and marketing sites.
          </p>
          {!hasAnyCoderPlan(auth) && (
            <p className="services-panel__error">
              Templates requires an active Vigthoria Coder subscription.{' '}
              <a href={CODER_UPGRADE_URL} target="_blank" rel="noreferrer">Upgrade</a>
            </p>
          )}
          <textarea
            className="services-panel__input"
            rows={4}
            placeholder="e.g. Modern gaming studio landing page with dark theme and hero video"
            value={prompt}
            onChange={(e) => setPrompt(e.target.value)}
          />
          <div className="services-panel__actions">
            <button type="button" className="is-primary" disabled={loading || !prompt.trim() || !hasAnyCoderPlan(auth)} onClick={() => void runTemplate()}>
              {loading ? 'Matching…' : 'Match template'}
            </button>
          </div>
          {error && <p className="services-panel__error">{error}</p>}
          {serviceResult && (
            <div
              className="services-panel__result markdown-body"
              dangerouslySetInnerHTML={{ __html: renderMarkdownHtml(serviceResult) }}
            />
          )}
        </div>
      )}
    </aside>
  );
}
