'use client';

import { motion } from 'framer-motion';
import {
  Brain, Wallet, Users, TrendingUp, Package, Eye, FolderKanban,
  FileText, Zap, ArrowDown, Network, Shield
} from 'lucide-react';

const DOMAIN_ICONS: Record<string, React.ElementType> = {
  ceo: Brain, finance: Wallet, hr: Users, sales: TrendingUp,
  inventory: Package, compliance: Eye, projects: FolderKanban, operations: FileText,
};

const MATURITY_LABELS = ['Newborn', 'Infant', 'Apprentice', 'Proficient', 'Expert', 'Master'];

interface AgentProfile {
  agentId: string;
  name: string;
  title: string;
  domain: string;
  parentAgentId: string | null;
  moduleId: string | null;
  moduleName: string;
  moduleEnabled: boolean;
  avatarColor: string;
  status: string;
  maturityLevel: number;
  xp: number;
  capabilities: string[];
  associatedModules: { moduleId: string; name: string; enabled: boolean }[];
}

interface HierarchyViewProps {
  profiles: AgentProfile[];
}

function HierarchyNode({ agent, isRoot }: { agent: AgentProfile; isRoot?: boolean }) {
  const Icon = DOMAIN_ICONS[agent.domain] || Brain;
  const enabledModCount = agent.associatedModules.filter(m => m.enabled).length;
  const totalModCount = agent.associatedModules.length;

  return (
    <motion.div
      initial={{ opacity: 0, y: 10 }}
      animate={{ opacity: 1, y: 0 }}
      className={`relative rounded-xl border p-4 transition-all duration-200 ${
        agent.status === 'active'
          ? 'bg-slate-800/80 border-slate-600/60 shadow-lg'
          : 'bg-slate-800/40 border-slate-700/30 opacity-60'
      } ${isRoot ? 'ring-2 ring-brand-deep/30 shadow-brand-deep/10 shadow-lg' : ''}`}
      style={{ minWidth: isRoot ? 280 : 200 }}
    >
      <div className="flex items-center gap-3">
        <div
          className={`${isRoot ? 'w-14 h-14' : 'w-10 h-10'} rounded-xl flex items-center justify-center shrink-0 relative`}
          style={{ backgroundColor: `${agent.avatarColor}15`, color: agent.avatarColor }}
        >
          <Icon className={isRoot ? 'w-7 h-7' : 'w-5 h-5'} />
          <span className={`absolute -bottom-0.5 -right-0.5 ${isRoot ? 'w-3.5 h-3.5' : 'w-2.5 h-2.5'} rounded-full border-2 border-slate-800 ${
            agent.status === 'active' ? 'bg-green-500' :
            agent.status === 'training' ? 'bg-amber-500' : 'bg-gray-500'
          }`} />
        </div>
        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-2">
            <h4 className={`${isRoot ? 'text-base' : 'text-sm'} font-bold text-white`}>{agent.name}</h4>
            {isRoot && (
              <span className="text-[8px] px-1.5 py-0.5 rounded bg-gradient-to-r from-brand-deep/20 to-brand-secondary/20 text-brand-light border border-brand-deep/30 font-bold">
                CEO
              </span>
            )}
          </div>
          <p className="text-[10px] text-gray-400">{agent.title}</p>
          <div className="flex items-center gap-2 mt-1">
            <span className="text-[8px] px-1.5 py-0.5 rounded bg-slate-700/50 text-gray-300">
              Lv.{agent.maturityLevel} {MATURITY_LABELS[agent.maturityLevel]} · {agent.xp}XP
            </span>
            {totalModCount > 0 && (
              <span className={`text-[8px] px-1.5 py-0.5 rounded ${
                enabledModCount === totalModCount
                  ? 'bg-green-500/10 text-green-400'
                  : 'bg-amber-500/10 text-amber-400'
              }`}>
                {enabledModCount}/{totalModCount} modules
              </span>
            )}
          </div>
        </div>
      </div>

      {/* Module assignments */}
      {agent.associatedModules.length > 0 && (
        <div className="mt-2 flex flex-wrap gap-1">
          {agent.associatedModules.map(m => (
            <span
              key={m.moduleId}
              className={`text-[8px] px-1.5 py-0.5 rounded ${
                m.enabled
                  ? 'bg-brand-deep/10 text-brand-light border border-brand-deep/15'
                  : 'bg-slate-700/30 text-gray-600 border border-slate-700/30 line-through'
              }`}
            >
              {m.name}
            </span>
          ))}
        </div>
      )}
    </motion.div>
  );
}

export function AgentHierarchyView({ profiles }: HierarchyViewProps) {
  const ceo = profiles.find(p => p.parentAgentId === null);
  const subAgents = profiles.filter(p => p.parentAgentId !== null);
  const activeCount = profiles.filter(p => p.status === 'active').length;
  const dormantCount = profiles.filter(p => p.status !== 'active').length;

  if (!ceo) {
    return (
      <div className="text-center py-12 text-gray-500">
        <Network className="w-8 h-8 mx-auto mb-2 opacity-50" />
        <p>No agent hierarchy initialized yet.</p>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Legend */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-4">
          <div className="flex items-center gap-1.5">
            <div className="w-2.5 h-2.5 rounded-full bg-green-500" />
            <span className="text-xs text-gray-400">Active ({activeCount})</span>
          </div>
          <div className="flex items-center gap-1.5">
            <div className="w-2.5 h-2.5 rounded-full bg-gray-500" />
            <span className="text-xs text-gray-400">Dormant ({dormantCount})</span>
          </div>
          <div className="flex items-center gap-1.5">
            <div className="w-2.5 h-2.5 rounded-full bg-amber-500" />
            <span className="text-xs text-gray-400">Training</span>
          </div>
        </div>
        <div className="text-xs text-gray-500 flex items-center gap-1">
          <Shield className="w-3 h-3" />
          Agents auto-activate/deactivate when modules are toggled
        </div>
      </div>

      {/* CEO Node */}
      <div className="flex justify-center">
        <HierarchyNode agent={ceo} isRoot />
      </div>

      {/* Connection lines from CEO to sub-agents */}
      <div className="flex justify-center">
        <div className="relative w-full max-w-5xl">
          {/* Vertical line from CEO */}
          <div className="absolute left-1/2 -translate-x-1/2 -top-2 w-0.5 h-8 bg-gradient-to-b from-brand-deep/60 to-brand-deep/20" />
          {/* Horizontal connector */}
          <div className="absolute top-6 left-[8%] right-[8%] h-0.5 bg-brand-deep/20" />
          {/* Vertical drops */}
          <div className="flex justify-between px-[6%] pt-6">
            {subAgents.map((_, i) => (
              <div key={i} className="flex justify-center" style={{ width: `${100 / subAgents.length}%` }}>
                <div className="w-0.5 h-6 bg-brand-deep/20" />
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Sub-Agent Grid */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-3">
        {subAgents.map(agent => (
          <HierarchyNode key={agent.agentId} agent={agent} />
        ))}
      </div>

      {/* Info Banner */}
      <div className="bg-gradient-to-r from-brand-secondary/5 via-brand-deep/5 to-brand-secondary/5 border border-brand-secondary/20 rounded-xl p-4">
        <div className="flex items-start gap-3">
          <Brain className="w-5 h-5 text-brand-secondary-light mt-0.5 shrink-0" />
          <div>
            <h4 className="text-sm font-semibold text-white">How the Agent Hierarchy Works</h4>
            <p className="text-xs text-gray-400 mt-1 leading-relaxed">
              Agent CEO (<span className="text-brand">Tes</span>) sits at the top, coordinating all domain-specific sub-agents.
              Each sub-agent owns a business domain and has persistent memory and autonomous reasoning.
              When a module is enabled, its corresponding agent activates. When disabled, the agent goes dormant.
              Cross-domain issues automatically escalate to Agent CEO for resolution.
              Agents gain XP through interactions and level up over time, becoming more effective.
            </p>
          </div>
        </div>
      </div>
    </div>
  );
}
