'use client';

import { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import {
  Brain, Sparkles, Code, Shield, TestTube,
  ChevronDown, ChevronRight, ArrowRight, Target,
  CheckCircle, Loader2, AlertTriangle, BookOpen,
  Lightbulb, FlaskConical, Wrench
} from 'lucide-react';

// ─── Types ────────────────────────────────────────────────────────

interface Agent {
  id: string;
  name: string;
  title: string;
  description: string;
  responsibilities: string[];
  parent: string | null;
  children: string[];
}

interface PreambleDirective {
  id: string;
  category: string;
  title: string;
  directive: string;
  appliesTo: 'all' | string[];
}

interface HierarchyData {
  pipeline: string;
  hierarchy: {
    root: { id: string; name: string; title: string; description: string };
    agents: Agent[];
  };
  qualityGate: { minReviewScore: number; minTestAccuracy: number; maxRemediationLoops: number };
  preambleDirectives?: PreambleDirective[];
}

interface AgentLogEntry {
  agent: string;
  action: string;
  timestamp: string;
  score?: number;
}

// ─── Icon Map ─────────────────────────────────────────────────────

const AGENT_ICON: Record<string, React.ReactNode> = {
  'architect':       <Brain className="w-5 h-5" />,
  'prompt-engineer': <Sparkles className="w-5 h-5" />,
  'code-engineer':   <Code className="w-5 h-5" />,
  'review-agent':    <Shield className="w-5 h-5" />,
  'qa-agent':        <TestTube className="w-5 h-5" />,
};

const AGENT_COLOR: Record<string, string> = {
  'architect':       'from-violet-500/20 to-violet-600/10 border-violet-500/30 text-violet-400',
  'prompt-engineer': 'from-sky-500/20 to-sky-600/10 border-sky-500/30 text-sky-400',
  'code-engineer':   'from-brand-deep/20 to-brand-secondary-deep/10 border-brand-deep/30 text-brand',
  'review-agent':    'from-amber-500/20 to-amber-600/10 border-amber-500/30 text-amber-400',
  'qa-agent':        'from-emerald-500/20 to-emerald-600/10 border-emerald-500/30 text-emerald-400',
};

const AGENT_GLOW: Record<string, string> = {
  'architect':       'shadow-violet-500/10',
  'prompt-engineer': 'shadow-sky-500/10',
  'code-engineer':   'shadow-brand-deep/10',
  'review-agent':    'shadow-amber-500/10',
  'qa-agent':        'shadow-emerald-500/10',
};

// ─── Quality Gate Badge ───────────────────────────────────────────

export function QualityGateBadge({ reviewScore, testAccuracy }: { reviewScore?: number; testAccuracy?: number }) {
  const threshold = 97;
  const reviewPass = reviewScore !== undefined && reviewScore >= threshold;
  const testPass = testAccuracy !== undefined && testAccuracy >= threshold;
  const pending = reviewScore === undefined && testAccuracy === undefined;

  return (
    <div className="flex items-center gap-3 px-4 py-3 rounded-xl bg-gradient-to-r from-brand-deep/5 to-emerald-500/5 border border-white/10">
      <Target className="w-5 h-5 text-brand" />
      <div className="flex-1">
        <div className="text-xs font-semibold uppercase tracking-wider text-gray-400 mb-1">Quality Gate — 97% Minimum</div>
        <div className="flex items-center gap-4">
          <div className="flex items-center gap-1.5">
            {pending ? (
              <div className="w-3.5 h-3.5 rounded-full bg-gray-600 border border-gray-500" />
            ) : reviewPass ? (
              <CheckCircle className="w-3.5 h-3.5 text-emerald-400" />
            ) : (
              <AlertTriangle className="w-3.5 h-3.5 text-amber-400" />
            )}
            <span className="text-sm text-gray-300">
              Code Review: {reviewScore !== undefined ? <span className={reviewPass ? 'text-emerald-400 font-semibold' : 'text-amber-400 font-semibold'}>{reviewScore}%</span> : <span className="text-gray-500">—</span>}
            </span>
          </div>
          <div className="flex items-center gap-1.5">
            {pending ? (
              <div className="w-3.5 h-3.5 rounded-full bg-gray-600 border border-gray-500" />
            ) : testPass ? (
              <CheckCircle className="w-3.5 h-3.5 text-emerald-400" />
            ) : (
              <AlertTriangle className="w-3.5 h-3.5 text-amber-400" />
            )}
            <span className="text-sm text-gray-300">
              Simulated Tests: {testAccuracy !== undefined ? <span className={testPass ? 'text-emerald-400 font-semibold' : 'text-amber-400 font-semibold'}>{testAccuracy}%</span> : <span className="text-gray-500">—</span>}
            </span>
          </div>
        </div>
      </div>
    </div>
  );
}

// ─── Agent Card ───────────────────────────────────────────────────

function AgentCard({ agent, isActive, isExpanded, onToggle }: {
  agent: Agent;
  isActive?: boolean;
  isExpanded: boolean;
  onToggle: () => void;
}) {
  const colorClass = AGENT_COLOR[agent.id] || 'from-gray-500/20 to-gray-600/10 border-gray-500/30 text-gray-400';
  const glowClass = AGENT_GLOW[agent.id] || '';

  return (
    <motion.div
      layout
      className={`rounded-xl border bg-gradient-to-br ${colorClass} ${isActive ? `shadow-lg ${glowClass}` : ''} transition-all cursor-pointer`}
      onClick={onToggle}
    >
      <div className="flex items-center gap-3 px-4 py-3">
        <div className="flex-shrink-0">
          {AGENT_ICON[agent.id] || <Brain className="w-5 h-5" />}
        </div>
        <div className="flex-1 min-w-0">
          <div className="text-sm font-semibold text-white">{agent.name}</div>
          <div className="text-xs text-gray-400 truncate">{agent.title}</div>
        </div>
        {isActive && (
          <Loader2 className="w-4 h-4 animate-spin text-brand" />
        )}
        {isExpanded ? (
          <ChevronDown className="w-4 h-4 text-gray-500" />
        ) : (
          <ChevronRight className="w-4 h-4 text-gray-500" />
        )}
      </div>
      <AnimatePresence>
        {isExpanded && (
          <motion.div
            initial={{ height: 0, opacity: 0 }}
            animate={{ height: 'auto', opacity: 1 }}
            exit={{ height: 0, opacity: 0 }}
            className="overflow-hidden"
          >
            <div className="px-4 pb-3 border-t border-white/5 pt-3">
              <p className="text-xs text-gray-400 mb-2">{agent.description}</p>
              <ul className="space-y-1">
                {agent.responsibilities.slice(0, 4).map((r, i) => (
                  <li key={i} className="flex items-start gap-1.5 text-xs text-gray-500">
                    <ArrowRight className="w-3 h-3 mt-0.5 flex-shrink-0" />
                    <span>{r}</span>
                  </li>
                ))}
              </ul>
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </motion.div>
  );
}

// ─── Agent Pipeline Flow ──────────────────────────────────────────

export function AgentPipelineFlow({ activeAgent, agentLog }: {
  activeAgent?: string;
  agentLog?: AgentLogEntry[];
}) {
  const PIPELINE_ORDER: Array<{ id: string; name: string }> = [
    { id: 'architect', name: 'Architect' },
    { id: 'prompt-engineer', name: 'Prompt Eng.' },
    { id: 'code-engineer', name: 'Code Eng.' },
    { id: 'review-agent', name: 'Review' },
    { id: 'qa-agent', name: 'QA' },
  ];

  const activeIdx = activeAgent ? PIPELINE_ORDER.findIndex(p => p.id === activeAgent) : -1;

  return (
    <div className="flex items-center gap-1 overflow-x-auto py-2">
      {PIPELINE_ORDER.map((agent, idx) => {
        const isActive = agent.id === activeAgent;
        const isCompleted = activeIdx > idx;
        const colorBase = AGENT_COLOR[agent.id]?.split(' ')[0] || 'from-gray-500/20';
        
        return (
          <div key={agent.id} className="flex items-center gap-1">
            <div
              className={`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium transition-all ${
                isActive
                  ? 'bg-gradient-to-r ' + colorBase + ' to-transparent border border-white/20 text-white shadow-lg'
                  : isCompleted
                  ? 'bg-white/5 border border-emerald-500/20 text-emerald-400'
                  : 'bg-white/5 border border-white/5 text-gray-500'
              }`}
            >
              {isCompleted ? (
                <CheckCircle className="w-3 h-3" />
              ) : isActive ? (
                <Loader2 className="w-3 h-3 animate-spin" />
              ) : (
                <div className="w-3 h-3 rounded-full border border-gray-600" />
              )}
              {agent.name}
            </div>
            {idx < PIPELINE_ORDER.length - 1 && (
              <ArrowRight className={`w-3 h-3 flex-shrink-0 ${isCompleted ? 'text-emerald-500/50' : 'text-gray-700'}`} />
            )}
          </div>
        );
      })}
    </div>
  );
}

// ─── Preamble Panel ───────────────────────────────────────────────

const CATEGORY_META: Record<string, { icon: React.ReactNode; label: string; color: string }> = {
  'constitution':      { icon: <BookOpen className="w-3.5 h-3.5" />,   label: 'Constitution',             color: 'text-red-400 bg-red-500/10 border-red-500/20' },
  'clean-code':        { icon: <Code className="w-3.5 h-3.5" />,       label: 'Clean Code',               color: 'text-violet-400 bg-violet-500/10 border-violet-500/20' },
  'testing':           { icon: <FlaskConical className="w-3.5 h-3.5" />, label: 'Testing & QA',            color: 'text-amber-400 bg-amber-500/10 border-amber-500/20' },
  'security':          { icon: <Shield className="w-3.5 h-3.5" />,     label: 'Security & Reliability',   color: 'text-emerald-400 bg-emerald-500/10 border-emerald-500/20' },
  'documentation':     { icon: <BookOpen className="w-3.5 h-3.5" />,   label: 'Documentation',            color: 'text-blue-400 bg-blue-500/10 border-blue-500/20' },
  'process':           { icon: <Wrench className="w-3.5 h-3.5" />,     label: 'Process & Collaboration',  color: 'text-orange-400 bg-orange-500/10 border-orange-500/20' },
  'architecture':      { icon: <Lightbulb className="w-3.5 h-3.5" />,  label: 'Architecture',             color: 'text-sky-400 bg-sky-500/10 border-sky-500/20' },
};

function PreamblePanel({ directives }: { directives: PreambleDirective[] }) {
  const [expanded, setExpanded] = useState(false);

  // Group by category
  const grouped = directives.reduce<Record<string, PreambleDirective[]>>((acc, d) => {
    (acc[d.category] = acc[d.category] || []).push(d);
    return acc;
  }, {});

  return (
    <div className="mb-4 rounded-xl border border-white/10 bg-gradient-to-br from-white/[0.03] to-white/[0.01] overflow-hidden">
      <button
        onClick={() => setExpanded(!expanded)}
        className="w-full flex items-center gap-3 px-4 py-3 hover:bg-white/[0.02] transition-colors"
      >
        <div className="w-8 h-8 rounded-lg bg-gradient-to-br from-brand-deep/20 to-amber-500/10 flex items-center justify-center">
          <BookOpen className="w-4 h-4 text-brand" />
        </div>
        <div className="flex-1 text-left">
          <div className="text-sm font-semibold text-white">The Hearth Constitution — Standing Orders</div>
          <div className="text-xs text-gray-500">{directives.length} immutable directives enforced on every generation</div>
        </div>
        {expanded ? (
          <ChevronDown className="w-4 h-4 text-gray-500" />
        ) : (
          <ChevronRight className="w-4 h-4 text-gray-500" />
        )}
      </button>
      <AnimatePresence>
        {expanded && (
          <motion.div
            initial={{ height: 0, opacity: 0 }}
            animate={{ height: 'auto', opacity: 1 }}
            exit={{ height: 0, opacity: 0 }}
            className="overflow-hidden"
          >
            <div className="px-4 pb-4 space-y-3 border-t border-white/5 pt-3">
              {Object.entries(grouped).map(([category, items]) => {
                const meta = CATEGORY_META[category] || CATEGORY_META['software-practice'];
                return (
                  <div key={category}>
                    <div className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full border text-xs font-medium mb-2 ${meta.color}`}>
                      {meta.icon}
                      {meta.label}
                    </div>
                    <div className="space-y-2 pl-1">
                      {items.map((d) => (
                        <div key={d.id} className="flex items-start gap-2">
                          <ArrowRight className="w-3 h-3 mt-1 flex-shrink-0 text-gray-600" />
                          <div>
                            <span className="text-xs font-medium text-gray-300">{d.title}:</span>{' '}
                            <span className="text-xs text-gray-500">{d.directive.slice(0, 180)}{d.directive.length > 180 ? '…' : ''}</span>
                          </div>
                        </div>
                      ))}
                    </div>
                  </div>
                );
              })}
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}

// ─── Full Agent Hierarchy Panel (for Dashboard) ──────────────────

export function AgentHierarchyPanel() {
  const [data, setData] = useState<HierarchyData | null>(null);
  const [loading, setLoading] = useState(true);
  const [expandedAgent, setExpandedAgent] = useState<string | null>(null);

  useEffect(() => {
    fetch('/api/dark-factory/agents')
      .then(r => r.json())
      .then(d => { setData(d); setLoading(false); })
      .catch(() => setLoading(false));
  }, []);

  if (loading) {
    return (
      <div className="glass-card p-6 rounded-xl border border-white/10 animate-pulse">
        <div className="h-6 bg-white/5 rounded w-48 mb-4" />
        <div className="space-y-3">
          {[1, 2, 3, 4, 5].map(i => <div key={i} className="h-14 bg-white/5 rounded-xl" />)}
        </div>
      </div>
    );
  }

  if (!data) return null;

  return (
    <div className="glass-card p-6 rounded-xl border border-white/10">
      <div className="flex items-center justify-between mb-4">
        <div className="flex items-center gap-3">
          <div className="w-10 h-10 rounded-xl bg-gradient-to-br from-violet-500/20 to-brand-deep/20 flex items-center justify-center">
            <Brain className="w-5 h-5 text-violet-400" />
          </div>
          <div>
            <h2 className="text-lg font-semibold text-white">Agent Hierarchy</h2>
            <p className="text-xs text-gray-500">Standalone Pipeline — No Corners Cut</p>
          </div>
        </div>
        <div className="flex items-center gap-1 px-3 py-1.5 rounded-full bg-emerald-500/10 border border-emerald-500/20">
          <Target className="w-3.5 h-3.5 text-emerald-400" />
          <span className="text-xs font-semibold text-emerald-400">≥ {data.qualityGate.minReviewScore}% Gate</span>
        </div>
      </div>

      {/* Pipeline flow visualization */}
      <div className="mb-4">
        <AgentPipelineFlow />
      </div>

      {/* Preamble Directives — Standing Orders */}
      {data.preambleDirectives && data.preambleDirectives.length > 0 && (
        <PreamblePanel directives={data.preambleDirectives} />
      )}

      {/* Agent cards */}
      <div className="space-y-2">
        {data.hierarchy.agents.map((agent) => (
          <AgentCard
            key={agent.id}
            agent={agent}
            isExpanded={expandedAgent === agent.id}
            onToggle={() => setExpandedAgent(expandedAgent === agent.id ? null : agent.id)}
          />
        ))}
      </div>

      {/* Quality Gate info */}
      <div className="mt-4 p-3 rounded-lg bg-white/5 border border-white/5">
        <div className="flex items-center gap-2 mb-2">
          <Shield className="w-4 h-4 text-amber-400" />
          <span className="text-sm font-medium text-white">Quality Gate Protocol</span>
        </div>
        <p className="text-xs text-gray-400">
          Every generation must pass both the Review Agent (code quality ≥ {data.qualityGate.minReviewScore}%) and QA Agent (simulated test accuracy ≥ {data.qualityGate.minTestAccuracy}%). 
          Each artifact is reviewed individually — no truncation, no blind spots. If an agent&apos;s LLM call fails, the gate blocks (never auto-passes).
          Failures trigger automatic remediation — up to {data.qualityGate.maxRemediationLoops} loops — before Tesa Aria escalates to human review.
          All agents operate under The Hearth Constitution — {data.preambleDirectives?.length || 0} immutable directives enforced on every generation.
        </p>
      </div>
    </div>
  );
}

export default AgentHierarchyPanel;
