'use client';

import { useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import {
  Brain, Wallet, Users, TrendingUp, Package, Eye, FolderKanban,
  FileText, ChevronDown, ChevronUp, Zap, Activity, MessageSquare,
  Shield, AlertTriangle, Cpu, Sparkles, Target
} 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;
  personality: string;
  capabilities: string[];
  escalationTriggers: string[];
  status: string;
  maturityLevel: number;
  xp: number;
  totalInteractions: number;
  lastActiveAt: string | null;
  memoryCount: number;
  messagesSent: number;
  messagesReceived: number;
  associatedModules: { moduleId: string; name: string; enabled: boolean }[];
}

export function AgentProfileCard({ agent }: { agent: AgentProfile }) {
  const [expanded, setExpanded] = useState(false);
  const Icon = DOMAIN_ICONS[agent.domain] || Brain;
  const xpProgress = agent.maturityLevel < 5 ? ((agent.xp % 100) / 100) * 100 : 100;

  return (
    <motion.div
      layout
      className={`rounded-xl border overflow-hidden transition-all duration-200 ${
        agent.status === 'active'
          ? 'bg-slate-800/80 border-slate-700/50 ring-1 ring-green-500/20'
          : 'bg-slate-800/50 border-slate-700/30 opacity-70'
      }`}
    >
      <div className="p-4">
        {/* Header */}
        <div className="flex items-start gap-3">
          <div
            className="w-12 h-12 rounded-xl flex items-center justify-center shrink-0 relative"
            style={{ backgroundColor: `${agent.avatarColor}15`, color: agent.avatarColor }}
          >
            <Icon className="w-6 h-6" />
            <span className={`absolute -bottom-0.5 -right-0.5 w-3 h-3 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="text-sm font-bold text-white">{agent.name}</h4>
              <span className={`text-[9px] font-medium px-1.5 py-0.5 rounded ${
                agent.status === 'active'
                  ? 'bg-green-500/10 text-green-400 border border-green-500/20'
                  : agent.status === 'training'
                  ? 'bg-amber-500/10 text-amber-400 border border-amber-500/20'
                  : 'bg-gray-500/10 text-gray-400 border border-gray-500/20'
              }`}>
                {agent.status.toUpperCase()}
              </span>
            </div>
            <p className="text-xs text-gray-400">{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.parentAgentId === null && (
                <span className="text-[9px] px-1.5 py-0.5 rounded bg-brand-deep/10 text-brand border border-brand/30">
                  CEO
                </span>
              )}
            </div>
          </div>
        </div>

        {/* XP Progress */}
        <div className="mt-3">
          <div className="flex items-center justify-between text-[9px] text-gray-500 mb-1">
            <span>Level {agent.maturityLevel} → {agent.maturityLevel < 5 ? agent.maturityLevel + 1 : 'MAX'}</span>
            <span>{Math.round(xpProgress)}%</span>
          </div>
          <div className="h-1.5 bg-slate-700/50 rounded-full overflow-hidden">
            <div
              className="h-full rounded-full transition-all duration-700"
              style={{ width: `${xpProgress}%`, backgroundColor: agent.avatarColor }}
            />
          </div>
        </div>

        {/* Stats Row */}
        <div className="grid grid-cols-3 gap-2 mt-3">
          <div className="text-center p-1.5 bg-slate-700/30 rounded-lg">
            <p className="text-xs font-semibold text-white">{agent.memoryCount}</p>
            <p className="text-[9px] text-gray-500">Memories</p>
          </div>
          <div className="text-center p-1.5 bg-slate-700/30 rounded-lg">
            <p className="text-xs font-semibold text-white">{agent.totalInteractions}</p>
            <p className="text-[9px] text-gray-500">Interactions</p>
          </div>
          <div className="text-center p-1.5 bg-slate-700/30 rounded-lg">
            <p className="text-xs font-semibold text-white">{agent.messagesSent + agent.messagesReceived}</p>
            <p className="text-[9px] text-gray-500">Messages</p>
          </div>
        </div>

        {/* Associated Modules */}
        <div className="mt-3">
          <span className="text-[9px] font-medium text-gray-500 uppercase tracking-wider">Assigned Modules</span>
          <div className="flex flex-wrap gap-1 mt-1">
            {agent.associatedModules.length > 0 ? (
              agent.associatedModules.map(m => (
                <span
                  key={m.moduleId}
                  className={`text-[9px] px-1.5 py-0.5 rounded border ${
                    m.enabled
                      ? 'bg-brand-deep/10 text-brand-light border-brand-deep/20'
                      : 'bg-slate-700/50 text-gray-500 border-slate-600/50'
                  }`}
                >
                  {m.name}
                </span>
              ))
            ) : (
              <span className="text-[9px] text-gray-500">Oversees all agents</span>
            )}
          </div>
        </div>

        {/* Expand Toggle */}
        <button
          onClick={() => setExpanded(!expanded)}
          className="mt-3 flex items-center gap-1 text-[10px] text-gray-500 hover:text-gray-300 transition-colors w-full justify-center"
        >
          {expanded ? <ChevronUp className="w-3 h-3" /> : <ChevronDown className="w-3 h-3" />}
          {expanded ? 'Hide Profile' : 'View Full Profile'}
        </button>

        {/* Expanded Details */}
        <AnimatePresence>
          {expanded && (
            <motion.div
              initial={{ opacity: 0, height: 0 }}
              animate={{ opacity: 1, height: 'auto' }}
              exit={{ opacity: 0, height: 0 }}
              className="mt-3 pt-3 border-t border-slate-700/50 space-y-3"
            >
              {/* Personality */}
              <div>
                <div className="flex items-center gap-1.5 mb-1">
                  <Sparkles className="w-3 h-3 text-brand-secondary-light" />
                  <span className="text-[10px] font-medium text-gray-400 uppercase tracking-wider">Personality</span>
                </div>
                <p className="text-xs text-gray-300 leading-relaxed italic">
                  &ldquo;{agent.personality.split('\n')[0]}&rdquo;
                </p>
              </div>

              {/* Capabilities */}
              <div>
                <div className="flex items-center gap-1.5 mb-1">
                  <Cpu className="w-3 h-3 text-brand" />
                  <span className="text-[10px] font-medium text-gray-400 uppercase tracking-wider">Capabilities</span>
                </div>
                <div className="flex flex-wrap gap-1">
                  {agent.capabilities.map(c => (
                    <span key={c} className="text-[9px] px-1.5 py-0.5 bg-brand-deep/10 text-brand-light rounded border border-brand-deep/15">
                      {c.replace(/_/g, ' ')}
                    </span>
                  ))}
                </div>
              </div>

              {/* Escalation Triggers */}
              {agent.escalationTriggers.length > 0 && (
                <div>
                  <div className="flex items-center gap-1.5 mb-1">
                    <AlertTriangle className="w-3 h-3 text-amber-400" />
                    <span className="text-[10px] font-medium text-gray-400 uppercase tracking-wider">Escalation Triggers</span>
                  </div>
                  <div className="flex flex-wrap gap-1">
                    {agent.escalationTriggers.map(t => (
                      <span key={t} className="text-[9px] px-1.5 py-0.5 bg-amber-500/10 text-amber-300 rounded border border-amber-500/15">
                        {t.replace(/_/g, ' ')}
                      </span>
                    ))}
                  </div>
                </div>
              )}
            </motion.div>
          )}
        </AnimatePresence>
      </div>

      {/* Bottom status bar */}
      <div className={`h-0.5 ${
        agent.status === 'active'
          ? 'bg-gradient-to-r from-green-500 via-brand-deep to-brand-secondary'
          : 'bg-slate-700'
      }`} />
    </motion.div>
  );
}
