import { Sidebar } from './Sidebar';
import { Search, Bell, Settings, LogOut, User as UserIcon, Plus, Calendar, ClipboardList, CheckCircle, Users, BookOpen, Zap, Clock, History as HistoryIcon, LayoutGrid, FileSpreadsheet, Building2 } from 'lucide-react';
import { useAuth } from '../context/AuthContext';
import { useState, useEffect, useRef } from 'react';
import { API_BASE_URL } from '../lib/config';
import { cn } from '../lib/utils';
import { motion, AnimatePresence } from 'framer-motion';

interface DashboardLayoutProps {
  children: React.ReactNode;
  activeItem: string;
  onItemClick: (id: string) => void;
}

export const DashboardLayout: React.FC<DashboardLayoutProps> = ({ 
  children, 
  activeItem, 
  onItemClick
}) => {
  const { user, logout } = useAuth();
  const [searchQuery, setSearchQuery] = useState('');
  const [isSearchOpen, setIsSearchOpen] = useState(false);
  const [events, setEvents] = useState<any[]>([]);
  const searchRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (searchRef.current && !searchRef.current.contains(event.target as Node)) {
        setIsSearchOpen(false);
      }
    };
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  useEffect(() => {
    if (isSearchOpen && events.length === 0) {
      fetch(API_BASE_URL + '/api/events')
        .then(res => res.json())
        .then(data => setEvents(Array.isArray(data) ? data : []))
        .catch(err => console.error('Search fetch failed:', err));
    }
  }, [isSearchOpen]);

  const navItems = [
    { id: 'dashboard', label: 'Dashboard', icon: LayoutGrid, description: 'Main overview and stats' },
    { id: 'approvals', label: 'Approvals', icon: CheckCircle, description: 'Review pending requests', roles: ['HOD', 'PRINCIPAL', 'ADMIN'] },
    { id: 'events', label: 'All Events', icon: ClipboardList, description: 'Browse institution events' },
    { id: 'checklist', label: 'Checklist', icon: Calendar, description: 'Audit and compliance view' },
    { id: 'history', label: 'History', icon: HistoryIcon, description: 'Event ledger and audit trail' },
    { id: 'user-management', label: 'Manage Users', icon: Users, description: 'User roles and access', roles: ['ADMIN'] },
    { id: 'classes', label: 'Classes', icon: BookOpen, description: 'Academic structure', roles: ['ADMIN'] },
    { id: 'manage-venues', label: 'Manage Venues', icon: Building2, description: 'Configure college venues and capacities', roles: ['ADMIN'] },
    { id: 'import-excel', label: 'Import Excel', icon: FileSpreadsheet, description: 'Bulk upload from response sheets', roles: ['ADMIN', 'PRINCIPAL'] },
    { id: 'automation', label: 'Automation', icon: Zap, description: 'Smart scheduling tools', roles: ['ADMIN', 'PRINCIPAL', 'HOD'] },
  ].filter(item => !item.roles || item.roles.includes(user?.role || ''));

  const filteredNav = searchQuery.length > 1 
    ? navItems.filter(item => item.label.toLowerCase().includes(searchQuery.toLowerCase()))
    : [];

  const filteredEvents = searchQuery.length > 1 
    ? events.filter(e => 
        e.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
        e.department?.toLowerCase().includes(searchQuery.toLowerCase())
      ).slice(0, 5)
    : [];

  const handleResultClick = (id: string, type: 'nav' | 'event') => {
    if (type === 'nav') {
      onItemClick(id);
    } else {
      // For events, we'll navigate to 'events' and we could potentially filter there
      onItemClick('events');
    }
    setSearchQuery('');
    setIsSearchOpen(false);
  };

  return (
    <div className="min-h-screen bg-[#FDFDFE]">
      <Sidebar 
        activeItem={activeItem} 
        onItemClick={onItemClick} 
      />
      <main className="ml-[18rem] min-h-screen transition-all duration-500 pr-8">
        {/* Header */}
        <header className="sticky top-0 z-40 bg-[#FDFDFE]/80 backdrop-blur-md py-6 flex items-center justify-between gap-8">
          <div className="flex-1 max-w-xl relative group" ref={searchRef}>
            <Search className="absolute left-4 top-1/2 -translate-y-1/2 w-4.5 h-4.5 text-slate-400 group-focus-within:text-brand-indigo transition-colors" />
            <input 
              type="text" 
              value={searchQuery}
              onChange={(e) => {
                setSearchQuery(e.target.value);
                setIsSearchOpen(true);
              }}
              onFocus={() => setIsSearchOpen(true)}
              placeholder="Search events, pages, or tools..." 
              className="w-full bg-white border border-slate-200/60 rounded-[1.25rem] py-3 pl-12 pr-4 text-sm font-medium focus:outline-none focus:ring-2 focus:ring-brand-indigo/10 focus:border-brand-indigo transition-all shadow-sm"
            />

            <AnimatePresence>
              {isSearchOpen && (filteredNav.length > 0 || filteredEvents.length > 0) && (
                <motion.div
                  initial={{ opacity: 0, y: 10 }}
                  animate={{ opacity: 1, y: 0 }}
                  exit={{ opacity: 0, y: 10 }}
                  className="absolute top-full left-0 right-0 mt-3 bg-white/95 backdrop-blur-xl border border-slate-100 rounded-[2rem] shadow-[0_20px_50px_rgba(0,0,0,0.1)] overflow-hidden z-50 p-2"
                >
                  {filteredNav.length > 0 && (
                    <div className="mb-2">
                      <p className="px-4 py-2 text-[10px] font-black uppercase tracking-widest text-slate-400">Navigation</p>
                      {filteredNav.map(item => (
                        <button
                          key={item.id}
                          onClick={() => handleResultClick(item.id, 'nav')}
                          className="w-full flex items-center gap-4 p-3 hover:bg-slate-50 rounded-2xl transition-all text-left group"
                        >
                          <div className="w-10 h-10 rounded-xl bg-brand-glow flex items-center justify-center text-brand-indigo group-hover:bg-brand-indigo group-hover:text-white transition-all">
                            <item.icon className="w-5 h-5" />
                          </div>
                          <div>
                            <p className="text-sm font-black text-brand-navy">{item.label}</p>
                            <p className="text-[10px] font-medium text-slate-400">{item.description}</p>
                          </div>
                        </button>
                      ))}
                    </div>
                  )}

                  {filteredEvents.length > 0 && (
                    <div>
                      <p className="px-4 py-2 text-[10px] font-black uppercase tracking-widest text-slate-400">Recent Events</p>
                      {filteredEvents.map(event => (
                        <button
                          key={event.id}
                          onClick={() => handleResultClick(event.id, 'event')}
                          className="w-full flex items-center gap-4 p-3 hover:bg-slate-50 rounded-2xl transition-all text-left group"
                        >
                          <div className={cn(
                            "w-10 h-10 rounded-xl flex items-center justify-center transition-all",
                            event.status === 'APPROVED' ? "bg-emerald-50 text-emerald-600" :
                            event.status === 'PENDING' || event.status === 'REQUESTED' ? "bg-amber-50 text-amber-600" : "bg-slate-50 text-slate-400"
                          )}>
                            <ClipboardList className="w-5 h-5" />
                          </div>
                          <div className="flex-1">
                            <p className="text-sm font-black text-brand-navy truncate max-w-[250px]">{event.title}</p>
                            <div className="flex items-center gap-2">
                              <span className="text-[9px] font-bold uppercase tracking-wider text-slate-400">{event.department}</span>
                              <span className={cn(
                                "text-[8px] font-black uppercase px-1.5 py-0.5 rounded",
                                event.status === 'APPROVED' ? "bg-emerald-50 text-emerald-600" :
                                event.status === 'PENDING' || event.status === 'REQUESTED' ? "bg-amber-50 text-amber-600" : "bg-slate-100 text-slate-400"
                              )}>{event.status}</span>
                            </div>
                          </div>
                          <Clock className="w-3.5 h-3.5 text-slate-300" />
                        </button>
                      ))}
                    </div>
                  )}
                </motion.div>
              )}
            </AnimatePresence>
          </div>
          
          <div className="flex items-center gap-4">
            <button 
              onClick={() => onItemClick('propose')}
              className="flex items-center gap-2 px-5 py-2.5 bg-brand-indigo text-white rounded-[1.25rem] text-sm font-black transition-all hover:shadow-lg hover:shadow-brand-indigo/20 hover:scale-[1.02]"
            >
              <Plus className="w-4 h-4" />
              New Event
            </button>

            <div className="flex items-center gap-1 bg-white p-1 rounded-2xl border border-slate-100 shadow-sm">
              <button className="p-2.5 rounded-xl hover:bg-slate-50 transition-all text-slate-500 relative">
                <Bell className="w-5 h-5" />
                <span className="absolute top-2.5 right-2.5 w-2 h-2 bg-red-500 rounded-full border-2 border-white" />
              </button>
            </div>
            
            <div className="flex items-center gap-3 bg-white pl-1 pr-4 py-1 rounded-[1.5rem] shadow-sm border border-slate-100">
              <div className="w-10 h-10 rounded-full bg-brand-glow flex items-center justify-center overflow-hidden border border-brand-indigo/10">
                <UserIcon className="w-5 h-5 text-brand-indigo" />
              </div>
              <div className="flex flex-col">
                <span className="text-xs font-black text-brand-navy leading-none mb-0.5">
                  {user?.fullName}
                </span>
                <span className="text-[10px] font-bold text-brand-indigo/60 uppercase tracking-wider">
                  {user?.role}
                </span>
              </div>
            </div>

            <button 
              onClick={logout}
              className="p-3 rounded-2xl bg-white border border-slate-100 text-slate-400 hover:text-red-500 hover:border-red-100 hover:bg-red-50 transition-all shadow-sm"
              title="Sign Out"
            >
              <LogOut className="w-5 h-5" />
            </button>
          </div>
        </header>

        <div className="pb-10">
          {children}
        </div>
      </main>
    </div>
  );
};
