import { useEffect, useState } from 'react';
import { formatGoaPayload } from '@/lib/goa-architect';
import { executeGoaPayload, fetchAstMetadataTree, formatExecutionResults, revisePayloadOnCompilerError } from '@/lib/goa-executor';
import { buildGoaPayloadWithPlanner } from '@/lib/goa-planner';
import { runGoaPipeline } from '@/lib/goa-pipeline';
import { GOA_TEMPLATE_CATALOG_V1 } from '@/lib/template-catalog';
import { fetchLiveTemplateCatalog } from '@/lib/template-catalog-sync';
import { isValidProjectRoot } from '@/lib/tauri-bridge';
import { templateMatch } from '@/lib/vigthoria-services';
import { useActiveWorkspace, useWorkbenchStore } from '@/features/workspace/WorkspaceStore';
import { CODER_UPGRADE_URL, hasHyperTierPlan } from '@/lib/plan-gate';
import type { TemplateCategoryCatalog } from '@/types/goa-orchestrator';

export function GoaOrchestratorPanel() {
  const settings = useWorkbenchStore((s) => s.settings);
  const auth = useWorkbenchStore((s) => s.auth);
  const workspace = useActiveWorkspace();

  const [prompt, setPrompt] = useState('');
  const [payloadJson, setPayloadJson] = useState('');
  const [phase, setPhase] = useState<'idle' | 'architect' | 'execute' | 'stabilize'>('idle');
  const [error, setError] = useState<string | null>(null);
  const [log, setLog] = useState<string | null>(null);
  const [catalog, setCatalog] = useState<TemplateCategoryCatalog[]>(GOA_TEMPLATE_CATALOG_V1);
  const [catalogMeta, setCatalogMeta] = useState<{ total: number; source: 'live' | 'static' }>({
    total: 188,
    source: 'static',
  });

  useEffect(() => {
    let cancelled = false;
    void (async () => {
      const token = auth.hasToken ? await useWorkbenchStore.getState().getAuthToken() : null;
      const live = await fetchLiveTemplateCatalog(
        settings.templateUrl || 'https://templates.vigthoria.io',
        token,
      );
      if (!cancelled) {
        setCatalog(live.catalog);
        setCatalogMeta({ total: live.totalTemplates, source: live.source });
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [auth.hasToken, settings.templateUrl]);

  const runArchitect = async () => {
    if (!workspace?.rootPath || !prompt.trim()) return;
    if (!hasHyperTierPlan(auth)) {
      setError('GOA requires an active Pro, Professional, Enterprise, or Master Admin Vigthoria Coder subscription. Upgrade at ' + CODER_UPGRADE_URL);
      return;
    }
    setPhase('architect');
    setError(null);
    setLog(null);
    try {
      const isExisting = await isValidProjectRoot(workspace.rootPath);
      let templateMatchMeta: { id: string; category: string; confidence: number } | null = null;
      if (!isExisting || /\b(template|landing|new|create)\b/i.test(prompt)) {
        const token = auth.hasToken ? await useWorkbenchStore.getState().getAuthToken() : null;
        const tm = await templateMatch(
          settings.templateUrl || 'https://templates.vigthoria.io',
          token,
          prompt,
        );
        const tpl = tm.template as { id?: string; category?: string } | undefined;
        if (tpl?.id) {
          templateMatchMeta = {
            id: tpl.id,
            category: tpl.category || '',
            confidence: typeof tm.confidence === 'number' ? tm.confidence : 0,
          };
        }
      }
      let astMetadata: Record<string, unknown> | null = null;
      const token = auth.hasToken ? await useWorkbenchStore.getState().getAuthToken() : null;
      if (isExisting && token) {
        astMetadata = await fetchAstMetadataTree({
          hyperloopUrl: settings.hyperloopUrl || 'https://hyperloop.vigthoria.io',
          token,
          workspaceRoot: workspace.rootPath,
          userPrompt: prompt,
        });
      }
      const payload = await buildGoaPayloadWithPlanner(
        {
          userPrompt: prompt,
          workspaceRoot: workspace.rootPath,
          isExistingProject: isExisting,
          astMetadata,
          templateMatch: templateMatchMeta,
        },
        settings.hyperloopUrl || 'https://hyperloop.vigthoria.io',
        token,
      );
      setPayloadJson(formatGoaPayload(payload));
      setLog(
        `Architect: ${payload.workspace_type} · ${payload.analysis.detected_framework} · ${payload.instructions.length} instruction(s)`,
      );
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : String(err));
    } finally {
      setPhase('idle');
    }
  };

  const runExecute = async () => {
    if (!workspace?.rootPath || !prompt.trim()) return;
    if (!hasHyperTierPlan(auth)) {
      setError('GOA requires an active Pro, Professional, Enterprise, or Master Admin Vigthoria Coder subscription. Upgrade at ' + CODER_UPGRADE_URL);
      return;
    }
    setPhase('execute');
    setError(null);
    try {
      const token = auth.hasToken ? await useWorkbenchStore.getState().getAuthToken() : null;
      const result = await runGoaPipeline({
        hyperloopUrl: settings.hyperloopUrl || 'https://hyperloop.vigthoria.io',
        templateUrl: settings.templateUrl || 'https://templates.vigthoria.io',
        token,
        workspaceRoot: workspace.rootPath,
        userPrompt: prompt,
      });
      setPayloadJson(result.payloadJson);
      setLog(result.summary);
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : String(err));
    } finally {
      setPhase('idle');
    }
  };

  const runExecuteFromJson = async () => {
    if (!workspace?.rootPath || !payloadJson.trim()) return;
    if (!hasHyperTierPlan(auth)) {
      setError('GOA requires an active Pro, Professional, Enterprise, or Master Admin Vigthoria Coder subscription. Upgrade at ' + CODER_UPGRADE_URL);
      return;
    }
    setPhase('execute');
    setError(null);
    try {
      const token = auth.hasToken ? await useWorkbenchStore.getState().getAuthToken() : null;
      const payload = JSON.parse(payloadJson);
      const ctx = {
        hyperloopUrl: settings.hyperloopUrl || 'https://hyperloop.vigthoria.io',
        templateUrl: settings.templateUrl || 'https://templates.vigthoria.io',
        token,
        workspaceRoot: workspace.rootPath,
        userPrompt: prompt,
      };
      let results = await executeGoaPayload(payload, ctx);
      const failed = results.find((r) => !r.success && r.layer === 'stabilization');
      if (failed?.error && token) {
        const revised = await revisePayloadOnCompilerError(payload, failed.error, ctx);
        if (revised) {
          setPayloadJson(formatGoaPayload(revised));
          results = await executeGoaPayload(revised, ctx);
        }
      }
      setLog(formatExecutionResults(results));
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : String(err));
    } finally {
      setPhase('idle');
    }
  };

  const busy = phase !== 'idle';

  return (
    <div className="services-panel__body goa-panel">
      <p className="services-panel__intro">
        GOA V1.0 — Architect routes Greenfield (template injection) vs Brownfield (AST scan). Templates are written to disk; existing index.html merges via HTML inject.
      </p>
      {!hasHyperTierPlan(auth) && (
        <p className="services-panel__error">
          GOA requires an active Pro, Professional, Enterprise, or Master Admin 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. Add Stripe billing to my Express app / Build a SaaS landing with auth"
        value={prompt}
        onChange={(e) => setPrompt(e.target.value)}
      />
      <div className="services-panel__actions">
        <button type="button" disabled={busy || !prompt.trim() || !hasHyperTierPlan(auth)} onClick={() => void runArchitect()}>
          {phase === 'architect' ? 'Architect…' : '1. Architect JSON'}
        </button>
        <button
          type="button"
          className="is-primary"
          disabled={busy || !prompt.trim() || !hasHyperTierPlan(auth)}
          onClick={() => void runExecute()}
        >
          {phase === 'execute' ? 'Executing…' : '2. Full pipeline'}
        </button>
        <button
          type="button"
          disabled={busy || !payloadJson.trim() || !hasHyperTierPlan(auth)}
          onClick={() => void runExecuteFromJson()}
        >
          Run JSON only
        </button>
      </div>
      <label className="goa-panel__label">Execution payload (JSON)</label>
      <textarea
        className="services-panel__input goa-panel__json"
        rows={12}
        spellCheck={false}
        value={payloadJson}
        onChange={(e) => setPayloadJson(e.target.value)}
        placeholder='{"workspace_type":"GREENFIELD","analysis":{...},"instructions":[...]}'
      />
      <details className="goa-panel__catalog">
        <summary>
          Template catalog ({catalogMeta.source}, {catalogMeta.total} total · {catalog.length} GOA categories)
        </summary>
        <ul>
          {catalog.map((cat) => (
            <li key={cat.category}>
              <strong>{cat.label}</strong> ({cat.count})
              <ul>
                {cat.templates.map((t) => (
                  <li key={t.id}>
                    <code>{t.id}</code> — vars: {t.variables.join(', ')}
                  </li>
                ))}
              </ul>
            </li>
          ))}
        </ul>
      </details>
      {error && <p className="services-panel__error">{error}</p>}
      {log && <pre className="goa-panel__log">{log}</pre>}
    </div>
  );
}
