import { useState, useEffect, useRef } from 'react';
import api from '../store/auth';
import { 
  Send, Mail, Inbox, SendHorizontal, Bell, 
  Search, X, MoreHorizontal, ChevronRight,
  MessageSquare, UserCircle, Clock, Trash2,
  Filter, Sparkles, Plus, AlertCircle,
  Archive, CheckCircle2, MoreVertical,
  GraduationCap, Users, Shield
} from 'lucide-react';

type Folder = 'inbox' | 'sent' | 'announcements';

interface Message {
  id: number;
  uid: string;
  sender_id: number;
  sender_name?: string;
  sender_email?: string;
  recipient_id: number;
  recipient_name?: string;
  recipient_email?: string;
  subject: string;
  body: string;
  is_read: number;
  is_announcement: number;
  priority: string;
  created_at: string;
}

export default function Messages() {
  const [messages, setMessages] = useState<Message[]>([]);
  const [activeFolder, setActiveFolder] = useState<Folder>('inbox');
  const [selectedMessage, setSelectedMessage] = useState<Message | null>(null);
  const [showCompose, setShowCompose] = useState(false);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [replyBody, setReplyBody] = useState('');
  
  const [contacts, setContacts] = useState<any[]>([]);
  const [form, setForm] = useState({ recipient_id: '', subject: '', body: '', is_announcement: false });

  const scrollRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    loadMessages();
    loadContacts();
  }, [activeFolder]);

  useEffect(() => {
    if (messages.length > 0 && !selectedMessage) {
        setSelectedMessage(messages[0]);
    }
  }, [messages, selectedMessage]);

  const loadMessages = async () => {
    setLoading(true);
    try {
      const res = await api.get('/messages', { params: { folder: activeFolder } });
      setMessages(res.data);
    } catch (err) {
      console.error('Failed to load transmission records');
    } finally {
      setLoading(false);
    }
  };

  const loadContacts = async () => {
    try {
        const res = await api.get('/messages/contacts');
        setContacts(res.data);
    } catch (err) {
        console.error('Failed to access system directory');
    }
  };

  const handleSend = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
        await api.post('/messages', form);
        setShowCompose(false);
        setForm({ recipient_id: '', subject: '', body: '', is_announcement: false });
        loadMessages();
    } catch (err) {
        alert('Failed to transmit message');
    }
  };

  const handleReply = async () => {
    if (!selectedMessage || !replyBody.trim()) return;
    try {
        await api.post(`/messages/${selectedMessage.id}/reply`, { body: replyBody });
        setReplyBody('');
        loadMessages();
    } catch (err) {
        alert('Failed to transmit response');
    }
  };

  const deleteMessage = async (id: number) => {
    if (!confirm('Archive this correspondence?')) return;
    try {
        await api.delete(`/messages/${id}`);
        setSelectedMessage(null);
        loadMessages();
    } catch (err) {
        alert('Failed to archive record');
    }
  };

  const filteredMessages = messages.filter(m => 
    m.subject.toLowerCase().includes(searchQuery.toLowerCase()) ||
    (m.sender_name || m.recipient_name || '').toLowerCase().includes(searchQuery.toLowerCase())
  );

  const unreadCount = messages.filter(m => !m.is_read).length;

  const stats = [
    { label: 'Inbox Volume', value: messages.length, icon: Inbox, color: 'blue', trend: 'Records' },
    { label: 'New Intel', value: unreadCount, icon: Bell, color: 'orange', trend: 'Unread' },
    { label: 'Broadcasts', value: messages.filter(m => m.is_announcement).length, icon: Sparkles, color: 'purple', trend: 'System' },
    { label: 'Transmitted', value: '42', icon: SendHorizontal, color: 'emerald', trend: 'Sent' },
  ];

  const getStatColors = (color: string) => {
    switch (color) {
      case 'blue': return 'bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400 border-blue-100 dark:border-blue-800';
      case 'orange': return 'bg-orange-50 dark:bg-orange-900/20 text-orange-600 dark:text-orange-400 border-orange-100 dark:border-orange-800';
      case 'purple': return 'bg-purple-50 dark:bg-purple-900/20 text-purple-600 dark:text-purple-400 border-purple-100 dark:border-purple-800';
      case 'emerald': return 'bg-emerald-50 dark:bg-emerald-900/20 text-emerald-600 dark:text-emerald-400 border-emerald-100 dark:border-emerald-800';
      default: return 'bg-muted text-text-muted border-border';
    }
  };

  return (
    <div className="h-[calc(100vh-120px)] flex flex-col space-y-8 animate-in fade-in duration-700">
      {/* Header Section */}
      <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 shrink-0">
        <div>
          <h2 className="text-3xl font-black text-text tracking-tight uppercase">Communication Hub</h2>
          <nav className="flex text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted gap-2 items-center mt-1">
            <span>NextGen Sync</span>
            <ChevronRight size={12} className="text-text-muted/30" />
            <span className="text-primary">Direct Messaging</span>
          </nav>
        </div>
        <div className="flex gap-3">
          <button className="flex items-center gap-2 px-5 py-2.5 bg-card border border-border text-text rounded-xl font-bold text-sm hover:bg-muted/50 transition-all shadow-sm active:scale-95">
            <Archive size={18} />
            Archive
          </button>
          <button 
            className="flex items-center gap-2 px-6 py-2.5 bg-primary text-white rounded-xl font-bold text-sm hover:bg-primary/90 transition-all shadow-lg shadow-blue-900/10 active:scale-95"
            onClick={() => setShowCompose(true)}
          >
            <Plus size={18} />
            Compose
          </button>
        </div>
      </div>

      {/* Stats Bento Grid */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 shrink-0">
        {stats.map((stat) => (
          <div key={stat.label} className="bg-card border border-border p-4 rounded-2xl flex items-center gap-4 hover:shadow-md transition-all group cursor-default">
            <div className={`w-10 h-10 rounded-xl flex items-center justify-center ${getStatColors(stat.color)} group-hover:scale-110 transition-transform`}>
              <stat.icon size={18} />
            </div>
            <div>
              <p className="text-[0.55rem] font-black uppercase tracking-wider text-text-muted">{stat.label}</p>
              <div className="flex items-baseline gap-2">
                <p className="text-lg font-black text-text">{stat.value}</p>
                <span className="text-[0.5rem] font-bold text-text-muted">{stat.trend}</span>
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* Main Messaging Interface */}
      <div className="flex-1 bg-card border border-border rounded-[2.5rem] shadow-sm overflow-hidden flex min-h-0">
        
        {/* Left Sidebar: Threads */}
        <div className="w-full lg:w-[400px] border-r border-border flex flex-col min-w-0">
          <div className="p-6 border-b border-border space-y-4 shrink-0">
            {/* Search */}
            <div className="relative group">
              <Search size={18} className="absolute left-4 top-1/2 -translate-y-1/2 text-text-muted group-focus-within:text-primary transition-colors" />
              <input 
                type="text" 
                className="w-full bg-muted/50 border border-border rounded-2xl pl-11 pr-4 py-3 text-sm font-medium focus:outline-none focus:ring-4 focus:ring-blue-500/5 focus:bg-card focus:border-primary transition-all text-text"
                placeholder="Search threads..."
                value={searchQuery}
                onChange={e => setSearchQuery(e.target.value)}
              />
            </div>

            {/* Folder Toggle */}
            <div className="flex p-1 bg-muted/50 rounded-xl border border-border">
                {(['inbox', 'sent', 'announcements'] as Folder[]).map(f => (
                    <button
                        key={f}
                        onClick={() => setActiveFolder(f)}
                        className={`flex-1 py-2 rounded-lg text-[0.6rem] font-black uppercase tracking-widest transition-all ${activeFolder === f ? 'bg-card text-primary shadow-sm ring-1 ring-border' : 'text-text-muted hover:text-text'}`}
                    >
                        {f}
                    </button>
                ))}
            </div>
          </div>

          {/* Thread List */}
          <div className="flex-1 overflow-y-auto custom-scrollbar">
            {loading ? (
                <div className="p-10 text-center">
                    <div className="w-8 h-8 border-3 border-primary border-t-transparent rounded-full animate-spin mx-auto mb-3"></div>
                    <p className="text-[0.6rem] font-black text-text-muted uppercase tracking-widest">Syncing Intel...</p>
                </div>
            ) : filteredMessages.length === 0 ? (
                <div className="p-10 text-center opacity-40 grayscale italic text-text-muted">
                    <MessageSquare size={32} className="mx-auto mb-3" />
                    <p className="text-xs font-bold uppercase tracking-widest">No transmissions found</p>
                </div>
            ) : filteredMessages.map(msg => (
                <div 
                    key={msg.id}
                    onClick={() => setSelectedMessage(msg)}
                    className={`p-6 border-b border-border cursor-pointer transition-all relative group ${selectedMessage?.id === msg.id ? 'bg-primary/5' : 'hover:bg-muted/30'}`}
                >
                    {selectedMessage?.id === msg.id && <div className="absolute left-0 top-0 bottom-0 w-1 bg-primary"></div>}
                    {!msg.is_read && activeFolder === 'inbox' && <div className="absolute top-6 right-6 w-2 h-2 rounded-full bg-primary shadow-lg shadow-blue-500/50 animate-pulse"></div>}
                    
                    <div className="flex gap-4">
                        <div className="w-12 h-12 rounded-2xl bg-muted flex items-center justify-center text-text-muted border border-border shadow-inner group-hover:scale-105 transition-transform shrink-0">
                            <UserCircle size={24} />
                        </div>
                        <div className="min-w-0 flex-1">
                            <div className="flex justify-between items-center mb-1">
                                <p className={`text-sm font-bold truncate ${selectedMessage?.id === msg.id ? 'text-primary' : 'text-text'}`}>
                                    {activeFolder === 'sent' ? msg.recipient_name : msg.sender_name || 'System'}
                                </p>
                                <span className="text-[0.6rem] font-bold text-text-muted font-mono">
                                    {new Date(msg.created_at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
                                </span>
                            </div>
                            <h4 className="text-xs font-black text-text-secondary mb-1 line-clamp-1 uppercase tracking-tight">{msg.subject}</h4>
                            <p className="text-xs text-text-muted line-clamp-2 leading-relaxed font-medium">
                                {msg.body}
                            </p>
                        </div>
                    </div>
                </div>
            ))}
          </div>
        </div>

        {/* Right Pane: Conversation Area */}
        <div className="hidden lg:flex flex-1 flex-col min-w-0 bg-muted/20">
            {selectedMessage ? (
                <>
                    {/* Toolbar */}
                    <div className="px-8 py-4 bg-card border-b border-border flex justify-between items-center shrink-0">
                        <div className="flex items-center gap-4">
                            <div className="w-10 h-10 rounded-xl bg-blue-50 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400 flex items-center justify-center border border-blue-100 dark:border-blue-800">
                                <Mail size={18} />
                            </div>
                            <div>
                                <h3 className="text-sm font-black text-text tracking-tight truncate max-w-[400px]">{selectedMessage.subject}</h3>
                                <p className="text-[0.6rem] font-bold text-text-muted uppercase tracking-widest mt-0.5">Ref: TXN-{selectedMessage.uid.split('-')[0]}</p>
                            </div>
                        </div>
                        <div className="flex items-center gap-2">
                            <button onClick={() => deleteMessage(selectedMessage.id)} className="p-2.5 text-text-muted hover:text-rose-500 hover:bg-rose-500/10 rounded-xl transition-all border border-transparent hover:border-rose-500/20">
                                <Trash2 size={18} />
                            </button>
                            <button className="p-2.5 text-text-muted hover:text-primary hover:bg-primary/5 rounded-xl transition-all">
                                <MoreVertical size={18} />
                            </button>
                        </div>
                    </div>

                    {/* Content */}
                    <div className="flex-1 overflow-y-auto p-10 space-y-10 custom-scrollbar" ref={scrollRef}>
                        {/* Sender Info */}
                        <div className="flex items-center justify-between pb-6 border-b border-border">
                            <div className="flex items-center gap-4">
                                <div className="w-14 h-14 rounded-2xl bg-gradient-to-br from-primary to-slate-900 flex items-center justify-center text-white text-lg font-black shadow-xl">
                                    {(selectedMessage.sender_name || 'S')[0]}
                                </div>
                                <div>
                                    <p className="text-lg font-black text-text">{selectedMessage.sender_name || 'System Administrator'}</p>
                                    <p className="text-[0.7rem] font-bold text-primary">{selectedMessage.sender_email || 'intel@nextgen.edu'}</p>
                                </div>
                            </div>
                            <div className="text-right">
                                <p className="text-[0.6rem] font-black text-text-muted uppercase tracking-[2px]">Transmission Time</p>
                                <p className="text-sm font-black text-text-secondary font-mono">{new Date(selectedMessage.created_at).toLocaleString()}</p>
                            </div>
                        </div>

                        {/* Message Body */}
                        <div className="bg-card rounded-[2rem] p-10 border border-border shadow-sm relative group overflow-hidden min-h-[200px]">
                            <div className="absolute top-0 right-0 w-32 h-32 bg-muted rounded-bl-[4rem] -mr-16 -mt-16 group-hover:bg-blue-50/10 dark:group-hover:bg-blue-900/10 transition-colors"></div>
                            <div className="relative z-10">
                                {selectedMessage.is_announcement ? (
                                    <div className="inline-flex items-center gap-2 px-3 py-1 bg-purple-50 dark:bg-purple-900/30 text-purple-600 dark:text-purple-400 rounded-lg border border-purple-100 dark:border-purple-800 text-[0.6rem] font-black uppercase tracking-widest mb-6">
                                        <Sparkles size={12} />
                                        System Broadcast
                                    </div>
                                ) : (
                                    <div className="inline-flex items-center gap-2 px-3 py-1 bg-emerald-50 dark:bg-emerald-900/30 text-emerald-600 dark:text-emerald-400 rounded-lg border border-emerald-100 dark:border-emerald-800 text-[0.6rem] font-black uppercase tracking-widest mb-6">
                                        <CheckCircle2 size={12} />
                                        Secure Direct
                                    </div>
                                )}
                                <p className="text-[1.05rem] text-text-secondary font-medium leading-relaxed whitespace-pre-wrap">
                                    {selectedMessage.body}
                                </p>
                            </div>
                        </div>

                        {/* Reply Composer */}
                        <div className="mt-auto pt-10">
                            <h4 className="text-[0.65rem] font-black uppercase tracking-[3px] text-text-muted mb-4 px-2">Secure Response</h4>
                            <div className="bg-card border border-border rounded-[2.5rem] p-2 shadow-xl shadow-blue-900/5 focus-within:ring-4 focus-within:ring-primary/5 transition-all">
                                <textarea 
                                    className="w-full bg-transparent border-none focus:ring-0 p-6 text-sm font-semibold text-text placeholder:text-text-muted/30 resize-none min-h-[120px]"
                                    placeholder="Type your response intelligence here..."
                                    value={replyBody}
                                    onChange={e => setReplyBody(e.target.value)}
                                />
                                <div className="flex justify-between items-center px-4 pb-4">
                                    <div className="flex gap-2">
                                        <button className="p-3 text-text-muted/30 hover:text-primary transition-colors"><MoreHorizontal size={20} /></button>
                                    </div>
                                    <button 
                                        onClick={handleReply}
                                        disabled={!replyBody.trim()}
                                        className="flex items-center gap-3 bg-primary hover:bg-primary-dark text-white px-8 py-3.5 rounded-2xl font-black text-[0.7rem] uppercase tracking-widest transition-all shadow-lg active:scale-95 disabled:opacity-50 disabled:grayscale"
                                    >
                                        Transmit Response
                                        <Send size={18} />
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </>
            ) : (
                <div className="flex-1 flex flex-col items-center justify-center gap-6 text-text-muted/30">
                    <div className="w-24 h-24 rounded-[2rem] bg-muted flex items-center justify-center border-2 border-dashed border-border">
                        <Inbox size={48} strokeWidth={1} />
                    </div>
                    <div className="text-center space-y-1">
                        <p className="text-xl font-black text-text-muted uppercase tracking-tighter">Communications Standby</p>
                        <p className="text-sm font-bold text-text-muted/50 uppercase tracking-widest">Select a transmission record to view details</p>
                    </div>
                </div>
            )}
        </div>
      </div>

      {/* Compose Modal */}
      {showCompose && (
        <div className="fixed inset-0 bg-[#002147]/60 backdrop-blur-sm z-[150] flex items-center justify-center p-4">
          <div className="bg-card rounded-[2.5rem] w-full max-w-xl shadow-2xl overflow-hidden animate-in zoom-in-95 duration-200 max-h-[90vh] flex flex-col border border-border">
            <div className="px-10 py-8 bg-muted/50 border-b border-border flex justify-between items-center relative overflow-hidden shrink-0">
              <div className="absolute right-[-20px] top-[-20px] opacity-[0.03] rotate-12">
                <Send size={180} />
              </div>
              <div className="relative z-10">
                <h2 className="text-2xl font-black text-text tracking-tight">New Transmission</h2>
                <p className="text-xs font-bold text-text-muted uppercase tracking-widest mt-1">Secure system correspondence</p>
              </div>
              <button onClick={() => setShowCompose(false)} className="relative z-10 w-10 h-10 flex items-center justify-center rounded-xl bg-card border border-border text-text-muted hover:text-rose-500 transition-all shadow-sm">
                <X size={20} />
              </button>
            </div>

            <form onSubmit={handleSend} className="p-10 space-y-6 overflow-y-auto flex-1 custom-scrollbar">
              <div className="space-y-1.5">
                <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Recipient Identifier</label>
                <div className="relative">
                    <Users size={16} className="absolute left-5 top-1/2 -translate-y-1/2 text-text-muted" />
                    <select 
                        className="form-input pl-12 appearance-none cursor-pointer text-text"
                        value={form.recipient_id} 
                        onChange={e => setForm({...form, recipient_id: e.target.value})} 
                        required
                    >
                        <option value="" className="text-text">Select registry entry...</option>
                        <optgroup label="Learners" className="text-text bg-card">
                            {contacts.filter(c => c.role === 'student').map(s => <option key={s.id} value={s.id}>{s.first_name} {s.last_name}</option>)}
                        </optgroup>
                        <optgroup label="Faculty" className="text-text bg-card">
                            {contacts.filter(c => c.role === 'teacher').map(t => <option key={t.id} value={t.id}>{t.first_name} {t.last_name}</option>)}
                        </optgroup>
                        <optgroup label="Admin" className="text-text bg-card">
                             {contacts.filter(c => c.role === 'admin').map(a => <option key={a.id} value={a.id}>{a.first_name} {a.last_name}</option>)}
                        </optgroup>
                    </select>
                </div>
              </div>

              <div className="space-y-1.5">
                <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Subject Header</label>
                <input className="form-input" value={form.subject} onChange={e => setForm({...form, subject: e.target.value})} placeholder="e.g., Performance Review: Physics 101" required />
              </div>

              <div className="space-y-1.5">
                <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Transmission Intel</label>
                <textarea className="form-input rounded-[2rem] px-5 py-5" rows={6} value={form.body} onChange={e => setForm({...form, body: e.target.value})} placeholder="Construct message content..." required />
              </div>

              <div className="flex items-center gap-3 p-4 bg-purple-50 dark:bg-purple-900/30 rounded-2xl border border-purple-100 dark:border-purple-800">
                <div className="w-10 h-10 rounded-xl bg-card border border-border flex items-center justify-center text-purple-600 dark:text-purple-400 shadow-sm"><Sparkles size={20} /></div>
                <div className="flex-1">
                    <p className="text-[0.65rem] font-black uppercase text-purple-600 dark:text-purple-400 tracking-widest">Broadcast Mode</p>
                    <p className="text-[0.6rem] font-bold text-purple-400 dark:text-purple-300">Transmit as priority system announcement</p>
                </div>
                <input 
                    type="checkbox" 
                    className="w-6 h-6 rounded-lg border-purple-200 dark:border-purple-700 text-purple-600 focus:ring-purple-500 cursor-pointer"
                    checked={form.is_announcement}
                    onChange={e => setForm({...form, is_announcement: e.target.checked})}
                />
              </div>

              <button type="submit" className="w-full py-5 bg-primary hover:bg-primary/90 text-white font-black uppercase tracking-widest text-xs rounded-[1.5rem] transition-all shadow-xl active:scale-95 flex items-center justify-center gap-3">
                <SendHorizontal size={18} />
                Finalize Transmission
              </button>
            </form>
          </div>
        </div>
      )}

      <style>{`
        .custom-scrollbar::-webkit-scrollbar { width: 4px; }
        .custom-scrollbar::-webkit-scrollbar-track { background: transparent; }
        .custom-scrollbar::-webkit-scrollbar-thumb { background: rgba(0, 71, 171, 0.1); border-radius: 10px; }
        .custom-scrollbar::-webkit-scrollbar-thumb:hover { background: rgba(0, 71, 171, 0.2); }
        .dark .custom-scrollbar::-webkit-scrollbar-thumb { background: rgba(255, 255, 255, 0.1); }
      `}</style>
    </div>
  );
}
