'use client';

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

const AGENT_COLORS: Record<string, string> = {
  'agent-ceo': '#0EA5E9',
  'agent-finance': '#22c55e',
  'agent-hr': '#f59e0b',
  'agent-sales': '#3b82f6',
  'agent-inventory': '#a855f7',
  'agent-compliance': '#ef4444',
  'agent-projects': '#14b8a6',
  'agent-operations': '#f97316',
  'agent-crm': '#ec4899',
};

const AGENT_INFO: Record<string, { name: string; title: string; domain: string }> = {
  'agent-ceo': { name: 'Tes', title: 'Chief Executive Officer', domain: 'ceo' },
  'agent-finance': { name: 'Ledger', title: 'Chief Financial Officer', domain: 'finance' },
  'agent-hr': { name: 'Harmony', title: 'Chief People Officer', domain: 'hr' },
  'agent-sales': { name: 'Pipeline', title: 'Chief Revenue Officer', domain: 'sales' },
  'agent-inventory': { name: 'Stockwatch', title: 'Chief Supply Chain Officer', domain: 'inventory' },
  'agent-compliance': { name: 'Sentinel', title: 'Chief Compliance Officer', domain: 'compliance' },
  'agent-projects': { name: 'Milestone', title: 'Chief Projects Officer', domain: 'projects' },
  'agent-operations': { name: 'Conductor', title: 'Chief Operations Officer', domain: 'operations' },
  'agent-crm': { name: 'Nexus', title: 'Chief Relationship Officer', domain: 'crm' },
};

interface ChatMessage {
  id: string;
  role: 'user' | 'agent';
  content: string;
  timestamp: string;
}

interface ATAFlyoutProps {
  agentId: string;
  isOpen: boolean;
  onClose: () => void;
}

export function ATAFlyout({ agentId, isOpen, onClose }: ATAFlyoutProps) {
  const [messages, setMessages] = useState<ChatMessage[]>([]);
  const [input, setInput] = useState('');
  const [sending, setSending] = useState(false);
  const scrollRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLInputElement>(null);

  const agent = AGENT_INFO[agentId];
  const color = AGENT_COLORS[agentId] || '#0EA5E9';
  const Icon = DOMAIN_ICONS[agent?.domain || 'ceo'] || Brain;

  // Initialize welcome message
  useEffect(() => {
    if (isOpen && agent) {
      setMessages([{
        id: 'welcome',
        role: 'agent',
        content: `Hey! I'm ${agent.name}, your ${agent.title}. What can I help you with in this section?`,
        timestamp: new Date().toISOString(),
      }]);
      setTimeout(() => inputRef.current?.focus(), 300);
    }
  }, [isOpen, agentId, agent]);

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

  const sendMessage = useCallback(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, message: userMsg.content }),
      });
      const data = await res.json();
      setMessages(prev => [...prev, {
        id: `agent_${Date.now()}`,
        role: 'agent',
        content: data.response || 'I\'m processing your request...',
        timestamp: new Date().toISOString(),
      }]);
    } catch {
      setMessages(prev => [...prev, {
        id: `err_${Date.now()}`,
        role: 'agent',
        content: 'Sorry, I hit a snag. Try again in a moment.',
        timestamp: new Date().toISOString(),
      }]);
    } finally {
      setSending(false);
    }
  }, [input, sending, agentId]);

  if (!agent) return null;

  return (
    <AnimatePresence>
      {isOpen && (
        <>
          {/* Backdrop */}
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 bg-black/40 backdrop-blur-sm z-[60]"
            onClick={onClose}
          />
          {/* Flyout Panel */}
          <motion.div
            initial={{ x: '100%' }}
            animate={{ x: 0 }}
            exit={{ x: '100%' }}
            transition={{ type: 'spring', damping: 25, stiffness: 300 }}
            className="fixed right-0 top-0 h-full w-[420px] max-w-[90vw] bg-[#0c1220] border-l border-white/10 z-[61] flex flex-col shadow-2xl"
          >
            {/* Header */}
            <div className="flex items-center justify-between px-5 py-4 border-b border-white/10"
                 style={{ background: `linear-gradient(135deg, ${color}15, transparent)` }}>
              <div className="flex items-center gap-3">
                <div className="relative">
                  <div className="w-10 h-10 rounded-full flex items-center justify-center"
                       style={{ backgroundColor: `${color}25`, border: `2px solid ${color}` }}>
                    <Icon className="w-5 h-5" style={{ color }} />
                  </div>
                  <div className="absolute -bottom-0.5 -right-0.5 w-3 h-3 rounded-full bg-green-500 border-2 border-[#0c1220]" />
                </div>
                <div>
                  <div className="flex items-center gap-2">
                    <span className="text-white font-semibold text-sm">{agent.name}</span>
                    <span className="text-[10px] px-1.5 py-0.5 rounded-full bg-green-500/20 text-green-400 font-medium">Online</span>
                  </div>
                  <span className="text-gray-400 text-xs">{agent.title}</span>
                </div>
              </div>
              <button onClick={onClose}
                      className="p-1.5 rounded-lg hover:bg-white/10 transition text-gray-400 hover:text-white">
                <X className="w-5 h-5" />
              </button>
            </div>

            {/* Chat Area */}
            <div ref={scrollRef} className="flex-1 overflow-y-auto p-4 space-y-3 scrollbar-hide">
              {messages.map((msg) => (
                <div key={msg.id}
                     className={`flex ${msg.role === 'user' ? 'justify-end' : 'justify-start'}`}>
                  <div className={`max-w-[85%] px-3.5 py-2.5 rounded-2xl text-sm leading-relaxed ${
                    msg.role === 'user'
                      ? 'bg-brand-primary/20 text-white rounded-br-md'
                      : 'bg-white/5 text-gray-200 rounded-bl-md'
                  }`}
                  style={msg.role === 'agent' ? { borderLeft: `3px solid ${color}` } : {}}>
                    {msg.content}
                  </div>
                </div>
              ))}
              {sending && (
                <div className="flex justify-start">
                  <div className="bg-white/5 px-4 py-3 rounded-2xl rounded-bl-md"
                       style={{ borderLeft: `3px solid ${color}` }}>
                    <div className="flex items-center gap-2">
                      <Loader2 className="w-3.5 h-3.5 animate-spin" style={{ color }} />
                      <span className="text-gray-400 text-sm">{agent.name} is thinking...</span>
                    </div>
                  </div>
                </div>
              )}
            </div>

            {/* Input */}
            <div className="border-t border-white/10 p-3">
              <div className="flex items-center gap-2 bg-white/5 rounded-xl px-3 py-2 focus-within:ring-1"
                   style={{ ['--tw-ring-color' as string]: color }}>
                <input
                  ref={inputRef}
                  value={input}
                  onChange={(e) => setInput(e.target.value)}
                  onKeyDown={(e) => e.key === 'Enter' && !e.shiftKey && sendMessage()}
                  placeholder={`Ask ${agent.name}...`}
                  className="flex-1 bg-transparent text-white text-sm placeholder:text-gray-500 outline-none"
                  disabled={sending}
                />
                <button
                  onClick={sendMessage}
                  disabled={!input.trim() || sending}
                  className="p-1.5 rounded-lg transition disabled:opacity-30"
                  style={{ color }}
                >
                  <Send className="w-4 h-4" />
                </button>
              </div>
              <p className="text-[10px] text-gray-600 mt-1.5 text-center">
                <Zap className="w-3 h-3 inline-block mr-1" style={{ color }} />
                Powered by {agent.name} &middot; Persistent Memory &middot; Autonomous Reasoning
              </p>
            </div>
          </motion.div>
        </>
      )}
    </AnimatePresence>
  );
}

// The ATA Button component to embed in each module section
interface ATAButtonProps {
  agentId: string;
  className?: string;
  variant?: 'default' | 'compact' | 'pill';
}

export function ATAButton({ agentId, className = '', variant = 'default' }: ATAButtonProps) {
  const [isOpen, setIsOpen] = useState(false);
  const agent = AGENT_INFO[agentId];
  const color = AGENT_COLORS[agentId] || '#0EA5E9';
  const Icon = DOMAIN_ICONS[agent?.domain || 'ceo'] || Brain;

  if (!agent) return null;

  if (variant === 'pill') {
    return (
      <>
        <button
          onClick={() => setIsOpen(true)}
          className={`inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-medium transition-all hover:scale-105 ${className}`}
          style={{
            backgroundColor: `${color}15`,
            border: `1px solid ${color}40`,
            color,
          }}
        >
          <Icon className="w-3 h-3" />
          Ask {agent.name}
        </button>
        <ATAFlyout agentId={agentId} isOpen={isOpen} onClose={() => setIsOpen(false)} />
      </>
    );
  }

  if (variant === 'compact') {
    return (
      <>
        <button
          onClick={() => setIsOpen(true)}
          className={`inline-flex items-center gap-2 px-3 py-2 rounded-lg text-xs font-medium transition-all hover:scale-[1.02] ${className}`}
          style={{
            backgroundColor: `${color}10`,
            border: `1px solid ${color}30`,
            color,
          }}
        >
          <Icon className="w-3.5 h-3.5" />
          <span>Ask {agent.name}</span>
          <ChevronRight className="w-3 h-3 opacity-60" />
        </button>
        <ATAFlyout agentId={agentId} isOpen={isOpen} onClose={() => setIsOpen(false)} />
      </>
    );
  }

  return (
    <>
      <button
        onClick={() => setIsOpen(true)}
        className={`group flex items-center gap-3 px-4 py-3 rounded-xl text-sm font-medium transition-all hover:scale-[1.02] ${className}`}
        style={{
          backgroundColor: `${color}10`,
          border: `1px solid ${color}25`,
        }}
      >
        <div className="w-8 h-8 rounded-full flex items-center justify-center shrink-0"
             style={{ backgroundColor: `${color}20` }}>
          <Icon className="w-4 h-4" style={{ color }} />
        </div>
        <div className="text-left">
          <div className="flex items-center gap-1.5">
            <span style={{ color }}>Ask {agent.name}</span>
            <Sparkles className="w-3 h-3 opacity-60" style={{ color }} />
          </div>
          <span className="text-[10px] text-gray-500 block">{agent.title}</span>
        </div>
        <ChevronRight className="w-4 h-4 ml-auto opacity-40 group-hover:opacity-80 transition" style={{ color }} />
      </button>
      <ATAFlyout agentId={agentId} isOpen={isOpen} onClose={() => setIsOpen(false)} />
    </>
  );
}
