'use client';

import { useState, useEffect, useCallback } from 'react';
import { motion } from 'framer-motion';
import {
  Brain, RefreshCw, Users, MessageSquare, Zap, AlertTriangle,
  Activity, Inbox
} from 'lucide-react';
import { AgentOrgChart } from './agent-org-chart';
import { AgentChatPanel } from './agent-chat-panel';

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 HierarchyStatus {
  agents: AgentData[];
  pendingEscalations: number;
  totalAgents: number;
  activeAgents: number;
  dormantAgents: number;
}

export function AgentDashboard() {
  const [data, setData] = useState<HierarchyStatus | null>(null);
  const [loading, setLoading] = useState(true);
  const [selectedAgentId, setSelectedAgentId] = useState<string | null>(null);
  const [activeTab, setActiveTab] = useState<'chat' | 'messages'>('chat');

  const fetchHierarchy = useCallback(async () => {
    try {
      const res = await fetch('/api/agents/hierarchy');
      const json = await res.json();
      if (json.agents) {
        setData(json);
        if (!selectedAgentId && json.agents.length > 0) {
          setSelectedAgentId('agent-ceo');
        }
      }
    } catch (err) {
      console.error('Failed to fetch agents:', err);
    } finally {
      setLoading(false);
    }
  }, [selectedAgentId]);

  useEffect(() => {
    fetchHierarchy();
  }, [fetchHierarchy]);

  const handleInit = async () => {
    setLoading(true);
    try {
      await fetch('/api/agents/hierarchy', { method: 'POST' });
      await fetchHierarchy();
    } finally {
      setLoading(false);
    }
  };

  const selectedAgent = data?.agents.find(a => a.agentId === selectedAgentId);

  if (loading && !data) {
    return (
      <div className="flex items-center justify-center h-64">
        <RefreshCw className="w-6 h-6 text-brand animate-spin" />
        <span className="ml-2 text-gray-400">Initializing agent hierarchy...</span>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Stats bar */}
      <div className="grid grid-cols-2 md:grid-cols-5 gap-3">
        <div className="bg-slate-800/60 border border-slate-700/50 rounded-xl p-3">
          <div className="flex items-center gap-2 text-brand">
            <Users className="w-4 h-4" />
            <span className="text-[10px] uppercase tracking-wider text-gray-400">Total Agents</span>
          </div>
          <p className="text-xl font-bold text-white mt-1">{data?.totalAgents || 0}</p>
        </div>
        <div className="bg-slate-800/60 border border-slate-700/50 rounded-xl p-3">
          <div className="flex items-center gap-2 text-green-400">
            <Activity className="w-4 h-4" />
            <span className="text-[10px] uppercase tracking-wider text-gray-400">Active</span>
          </div>
          <p className="text-xl font-bold text-white mt-1">{data?.activeAgents || 0}</p>
        </div>
        <div className="bg-slate-800/60 border border-slate-700/50 rounded-xl p-3">
          <div className="flex items-center gap-2 text-gray-400">
            <Zap className="w-4 h-4" />
            <span className="text-[10px] uppercase tracking-wider text-gray-400">Dormant</span>
          </div>
          <p className="text-xl font-bold text-white mt-1">{data?.dormantAgents || 0}</p>
        </div>
        <div className="bg-slate-800/60 border border-slate-700/50 rounded-xl p-3">
          <div className="flex items-center gap-2 text-amber-400">
            <AlertTriangle className="w-4 h-4" />
            <span className="text-[10px] uppercase tracking-wider text-gray-400">Escalations</span>
          </div>
          <p className="text-xl font-bold text-white mt-1">{data?.pendingEscalations || 0}</p>
        </div>
        <div className="bg-slate-800/60 border border-slate-700/50 rounded-xl p-3">
          <div className="flex items-center gap-2 text-brand-secondary-light">
            <Brain className="w-4 h-4" />
            <span className="text-[10px] uppercase tracking-wider text-gray-400">Total XP</span>
          </div>
          <p className="text-xl font-bold text-white mt-1">
            {data?.agents.reduce((sum, a) => sum + a.xp, 0) || 0}
          </p>
        </div>
      </div>

      {/* Org Chart */}
      <div className="bg-slate-800/30 border border-slate-700/30 rounded-xl p-4">
        <div className="flex items-center justify-between mb-4">
          <h3 className="text-sm font-semibold text-white flex items-center gap-2">
            <Brain className="w-4 h-4 text-brand" />
            Agent Hierarchy
          </h3>
          <button
            onClick={handleInit}
            className="flex items-center gap-1.5 px-3 py-1.5 text-xs bg-slate-800/40 border border-slate-700/50 text-gray-400 hover:text-brand rounded-lg transition-colors"
          >
            <RefreshCw className={`w-3.5 h-3.5 ${loading ? 'animate-spin' : ''}`} />
            Sync Agents
          </button>
        </div>
        {data && (
          <AgentOrgChart
            agents={data.agents}
            selectedAgentId={selectedAgentId}
            onSelectAgent={setSelectedAgentId}
          />
        )}
      </div>

      {/* Chat / Messages panel */}
      {selectedAgent && (
        <div>
          <div className="flex items-center gap-2 mb-3">
            <button
              onClick={() => setActiveTab('chat')}
              className={`flex items-center gap-1.5 px-3 py-1.5 text-xs rounded-lg border transition-colors ${
                activeTab === 'chat'
                  ? 'bg-brand-deep/10 border-brand-deep/30 text-brand'
                  : 'bg-slate-800/40 border-slate-700/50 text-gray-400 hover:text-gray-200'
              }`}
            >
              <MessageSquare className="w-3.5 h-3.5" /> Chat with {selectedAgent.name}
            </button>
            <button
              onClick={() => setActiveTab('messages')}
              className={`flex items-center gap-1.5 px-3 py-1.5 text-xs rounded-lg border transition-colors ${
                activeTab === 'messages'
                  ? 'bg-brand-deep/10 border-brand-deep/30 text-brand'
                  : 'bg-slate-800/40 border-slate-700/50 text-gray-400 hover:text-gray-200'
              }`}
            >
              <Inbox className="w-3.5 h-3.5" /> Inbox
            </button>
          </div>

          {activeTab === 'chat' && <AgentChatPanel agent={selectedAgent} />}
          {activeTab === 'messages' && <AgentInbox agentId={selectedAgent.agentId} />}
        </div>
      )}
    </div>
  );
}

// Simple inbox component
function AgentInbox({ agentId }: { agentId: string }) {
  const [messages, setMessages] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    (async () => {
      try {
        const res = await fetch(`/api/agents/messages?agentId=${agentId}`);
        const data = await res.json();
        setMessages(data.messages || []);
      } catch (err) {
        console.error('Failed to fetch messages:', err);
      } finally {
        setLoading(false);
      }
    })();
  }, [agentId]);

  if (loading) return <div className="text-gray-400 text-sm p-4">Loading messages...</div>;

  if (messages.length === 0) {
    return (
      <div className="bg-slate-800/40 rounded-xl border border-slate-700/50 p-6 text-center">
        <Inbox className="w-8 h-8 text-gray-600 mx-auto mb-2" />
        <p className="text-sm text-gray-500">No messages yet. Inter-agent messages and escalations will appear here.</p>
      </div>
    );
  }

  const priorityColors: Record<string, string> = {
    urgent: 'border-l-red-500 bg-red-500/5',
    high: 'border-l-amber-500 bg-amber-500/5',
    normal: 'border-l-blue-500 bg-blue-500/5',
    low: 'border-l-gray-500 bg-gray-500/5',
  };

  return (
    <div className="space-y-2">
      {messages.map((msg: any) => (
        <div
          key={msg.id}
          className={`rounded-lg border-l-4 border border-slate-700/30 p-3 ${priorityColors[msg.priority] || priorityColors.normal}`}
        >
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2">
              <span className="text-xs font-medium" style={{ color: msg.fromAgent?.avatarColor }}>
                {msg.fromAgent?.name || msg.fromAgentId}
              </span>
              <span className={`text-[9px] px-1.5 py-0.5 rounded ${
                msg.type === 'escalation' ? 'bg-red-500/10 text-red-400' :
                msg.type === 'report' ? 'bg-blue-500/10 text-blue-400' :
                'bg-gray-500/10 text-gray-400'
              }`}>{msg.type}</span>
            </div>
            <span className="text-[9px] text-gray-500">
              {new Date(msg.createdAt).toLocaleString()}
            </span>
          </div>
          <p className="text-sm text-white mt-1 font-medium">{msg.subject}</p>
          <p className="text-xs text-gray-400 mt-1">
            {typeof msg.content === 'string' ? msg.content : JSON.stringify(msg.content).substring(0, 200)}
          </p>
        </div>
      ))}
    </div>
  );
}
