'use client';

import { useState, useRef, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import {
  Send, Brain, Wallet, Users, TrendingUp, Package, Eye,
  FolderKanban, FileText, Loader2, AlertTriangle, Zap, MessageSquare
} 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,
};

interface ChatMessage {
  id: string;
  role: 'user' | 'agent';
  content: string;
  agentName?: string;
  agentColor?: string;
  escalated?: boolean;
  timestamp: string;
}

interface AgentData {
  agentId: string;
  name: string;
  title: string;
  domain: string;
  status: string;
  avatarColor: string;
  maturityLevel: number;
  xp: number;
  totalInteractions: number;
  memoryCount: number;
}

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

interface AgentChatPanelProps {
  agent: AgentData;
}

export function AgentChatPanel({ agent }: AgentChatPanelProps) {
  const [messages, setMessages] = useState<ChatMessage[]>([]);
  const [input, setInput] = useState('');
  const [sending, setSending] = useState(false);
  const scrollRef = useRef<HTMLDivElement>(null);
  const Icon = DOMAIN_ICONS[agent.domain] || Brain;

  useEffect(() => {
    // Reset chat when agent changes
    setMessages([{
      id: 'welcome',
      role: 'agent',
      content: `Hello! I'm ${agent.name}, your ${agent.title}. I have ${agent.memoryCount} memories and ${agent.totalInteractions} interactions under my belt. How can I help you today?`,
      agentName: agent.name,
      agentColor: agent.avatarColor,
      timestamp: new Date().toISOString(),
    }]);
  }, [agent.agentId, agent.name, agent.title, agent.memoryCount, agent.totalInteractions]);

  useEffect(() => {
    scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight, behavior: 'smooth' });
  }, [messages]);

  const sendMessage = async () => {
    if (!input.trim() || sending) return;

    const userMsg: ChatMessage = {
      id: `user_${Date.now()}`,
      role: 'user',
      content: input.trim(),
      timestamp: new Date().toISOString(),
    };
    setMessages(prev => [...prev, userMsg]);
    setInput('');
    setSending(true);

    try {
      const res = await fetch('/api/agents/chat', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ agentId: agent.agentId, message: userMsg.content }),
      });
      const data = await res.json();

      if (res.ok) {
        const agentMsg: ChatMessage = {
          id: `agent_${Date.now()}`,
          role: 'agent',
          content: data.reply,
          agentName: data.agentName,
          agentColor: data.avatarColor,
          escalated: data.escalated,
          timestamp: new Date().toISOString(),
        };
        setMessages(prev => [...prev, agentMsg]);
      } else {
        setMessages(prev => [...prev, {
          id: `error_${Date.now()}`,
          role: 'agent',
          content: data.error || 'Something went wrong.',
          agentName: 'System',
          agentColor: '#ef4444',
          timestamp: new Date().toISOString(),
        }]);
      }
    } catch {
      setMessages(prev => [...prev, {
        id: `error_${Date.now()}`,
        role: 'agent',
        content: 'Communication failed. Please try again.',
        agentName: 'System',
        agentColor: '#ef4444',
        timestamp: new Date().toISOString(),
      }]);
    } finally {
      setSending(false);
    }
  };

  return (
    <div className="flex flex-col h-full bg-slate-800/40 rounded-xl border border-slate-700/50 overflow-hidden">
      {/* Agent header */}
      <div className="p-4 border-b border-slate-700/50">
        <div className="flex items-center gap-3">
          <div
            className="w-10 h-10 rounded-full flex items-center justify-center"
            style={{ backgroundColor: `${agent.avatarColor}20`, color: agent.avatarColor }}
          >
            <Icon className="w-5 h-5" />
          </div>
          <div className="flex-1">
            <div className="flex items-center gap-2">
              <span className="text-sm font-semibold text-white">{agent.name}</span>
              <span className={`w-2 h-2 rounded-full ${
                agent.status === 'active' ? 'bg-green-400' : 'bg-gray-500'
              }`} />
              <span className="text-[10px] px-1.5 py-0.5 rounded bg-slate-700/50 text-gray-300">
                {MATURITY_LABELS[agent.maturityLevel]} · L{agent.maturityLevel}
              </span>
            </div>
            <p className="text-xs text-gray-400">{agent.title}</p>
          </div>
          <div className="text-right">
            <div className="text-[10px] text-gray-500">{agent.xp} XP</div>
            <div className="text-[10px] text-brand-secondary-light">{agent.memoryCount} memories</div>
          </div>
        </div>
      </div>

      {/* Messages */}
      <div ref={scrollRef} className="flex-1 overflow-y-auto p-4 space-y-3 min-h-0" style={{ maxHeight: '400px' }}>
        <AnimatePresence>
          {messages.map(msg => (
            <motion.div
              key={msg.id}
              initial={{ opacity: 0, y: 10 }}
              animate={{ opacity: 1, y: 0 }}
              className={`flex ${msg.role === 'user' ? 'justify-end' : 'justify-start'}`}
            >
              <div className={`max-w-[85%] rounded-lg px-3 py-2 ${
                msg.role === 'user'
                  ? 'bg-brand-deep/20 text-brand-light border border-brand-deep/20'
                  : 'bg-slate-700/50 text-gray-200 border border-slate-600/30'
              }`}>
                {msg.role === 'agent' && msg.agentName && (
                  <div className="flex items-center gap-1.5 mb-1">
                    <span className="text-[10px] font-medium" style={{ color: msg.agentColor }}>
                      {msg.agentName}
                    </span>
                    {msg.escalated && (
                      <span className="text-[9px] px-1 py-0.5 bg-amber-500/10 text-amber-400 rounded flex items-center gap-0.5">
                        <AlertTriangle className="w-2.5 h-2.5" /> Escalated
                      </span>
                    )}
                  </div>
                )}
                <p className="text-sm whitespace-pre-wrap">{msg.content}</p>
              </div>
            </motion.div>
          ))}
        </AnimatePresence>
        {sending && (
          <div className="flex justify-start">
            <div className="bg-slate-700/50 rounded-lg px-3 py-2 border border-slate-600/30">
              <Loader2 className="w-4 h-4 animate-spin text-brand" />
            </div>
          </div>
        )}
      </div>

      {/* Input */}
      <div className="p-3 border-t border-slate-700/50">
        <div className="flex items-center gap-2">
          <input
            type="text"
            value={input}
            onChange={e => setInput(e.target.value)}
            onKeyDown={e => e.key === 'Enter' && sendMessage()}
            placeholder={`Ask ${agent.name}...`}
            className="flex-1 bg-slate-900/50 border border-slate-700/50 rounded-lg px-3 py-2 text-sm text-white placeholder:text-gray-500 focus:outline-none focus:ring-1 focus:ring-brand-deep/50"
            disabled={sending || agent.status === 'dormant'}
          />
          <button
            onClick={sendMessage}
            disabled={sending || !input.trim() || agent.status === 'dormant'}
            className="p-2 bg-brand-deep/20 hover:bg-brand-deep/30 text-brand rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
          >
            <Send className="w-4 h-4" />
          </button>
        </div>
      </div>
    </div>
  );
}
