'use client';

import { motion } from 'framer-motion';
import {
  Brain, Wallet, Users, TrendingUp, Package, Eye, FolderKanban,
  FileText, MessageSquare, Zap, ChevronDown
} 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 STATUS_STYLES: Record<string, string> = {
  active: 'ring-2 ring-green-500/50',
  dormant: 'ring-2 ring-gray-600/50 opacity-50',
  training: 'ring-2 ring-amber-500/50',
};

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

interface AgentData {
  agentId: string;
  name: string;
  title: string;
  domain: string;
  status: string;
  parentAgentId: string | null;
  moduleId: string | null;
  avatarColor: string;
  maturityLevel: number;
  xp: number;
  totalInteractions: number;
  lastActiveAt: string | null;
  memoryCount: number;
  messagesSent: number;
  messagesReceived: number;
}

interface OrgChartProps {
  agents: AgentData[];
  selectedAgentId: string | null;
  onSelectAgent: (agentId: string) => void;
}

function AgentNode({ agent, isSelected, onClick }: { agent: AgentData; isSelected: boolean; onClick: () => void }) {
  const Icon = DOMAIN_ICONS[agent.domain] || Brain;
  const xpToNextLevel = ((agent.maturityLevel + 1) * 100) - agent.xp;
  const xpProgress = agent.maturityLevel < 5 ? ((agent.xp % 100) / 100) * 100 : 100;

  return (
    <motion.button
      whileHover={{ scale: 1.02 }}
      whileTap={{ scale: 0.98 }}
      onClick={onClick}
      className={`relative p-3 rounded-xl border transition-all duration-200 text-left w-full ${
        isSelected
          ? 'bg-slate-700/80 border-brand-deep/50 shadow-lg shadow-brand-deep/10'
          : 'bg-slate-800/60 border-slate-700/50 hover:border-slate-600'
      } ${STATUS_STYLES[agent.status] || ''}`}
    >
      <div className="flex items-center gap-3">
        <div
          className="w-10 h-10 rounded-full flex items-center justify-center shrink-0"
          style={{ backgroundColor: `${agent.avatarColor}20`, color: agent.avatarColor }}
        >
          <Icon className="w-5 h-5" />
        </div>
        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-2">
            <span className="text-sm font-semibold text-white truncate">{agent.name}</span>
            <span className={`w-2 h-2 rounded-full shrink-0 ${
              agent.status === 'active' ? 'bg-green-400' :
              agent.status === 'dormant' ? 'bg-gray-500' : 'bg-amber-400'
            }`} />
          </div>
          <p className="text-[10px] text-gray-400 truncate">{agent.title}</p>
          <div className="flex items-center gap-2 mt-1">
            <span className="text-[9px] px-1.5 py-0.5 rounded bg-slate-700/50 text-gray-300">
              {MATURITY_LABELS[agent.maturityLevel]} · {agent.xp} XP
            </span>
            {agent.memoryCount > 0 && (
              <span className="text-[9px] text-brand-secondary-light">
                {agent.memoryCount} memories
              </span>
            )}
          </div>
        </div>
      </div>
      {/* XP bar */}
      <div className="mt-2 h-1 bg-slate-700 rounded-full overflow-hidden">
        <div
          className="h-full rounded-full transition-all duration-500"
          style={{
            width: `${xpProgress}%`,
            backgroundColor: agent.avatarColor,
          }}
        />
      </div>
    </motion.button>
  );
}

export function AgentOrgChart({ agents, selectedAgentId, onSelectAgent }: OrgChartProps) {
  const ceo = agents.find(a => a.domain === 'ceo');
  const subAgents = agents.filter(a => a.parentAgentId === 'agent-ceo');

  if (!ceo) return null;

  return (
    <div className="space-y-4">
      {/* CEO */}
      <div className="max-w-xs mx-auto">
        <AgentNode
          agent={ceo}
          isSelected={selectedAgentId === ceo.agentId}
          onClick={() => onSelectAgent(ceo.agentId)}
        />
      </div>

      {/* Connection line */}
      <div className="flex justify-center">
        <div className="w-0.5 h-6 bg-gradient-to-b from-brand-deep/50 to-transparent" />
      </div>

      {/* Sub-agents grid */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-3">
        {subAgents.map(agent => (
          <AgentNode
            key={agent.agentId}
            agent={agent}
            isSelected={selectedAgentId === agent.agentId}
            onClick={() => onSelectAgent(agent.agentId)}
          />
        ))}
      </div>
    </div>
  );
}
