import React, { useState, useEffect } from 'react';
import { NavLink, useLocation, useNavigate } from 'react-router-dom';
import { 
  LayoutDashboard, Users, UserCircle, Bell, Search, Menu, X, LogOut, 
  Hexagon, Settings, Building2, Sun, Moon, Loader2 
} from 'lucide-react';
import { getAttendances, getUsers, getUserById, logout, searchGlobal } from '../services/dataService';
import { User } from '../types';

const SidebarItem = ({ to, icon: Icon, label, collapsed }: { to: string, icon: any, label: string, collapsed: boolean }) => (
  <NavLink
    to={to}
    className={({ isActive }) =>
      `flex items-center gap-3 px-4 py-3 rounded-xl transition-all duration-200 group ${
        isActive
          ? 'bg-brand-yellow text-zinc-950 font-semibold shadow-md shadow-brand-yellow/20'
          : 'text-zinc-500 dark:text-dark-muted hover:bg-zinc-100 dark:hover:bg-dark-border hover:text-zinc-900 dark:hover:text-dark-text'
      }`
    }
  >
    <Icon size={20} className="shrink-0" />
    {!collapsed && <span>{label}</span>}
  </NavLink>
);

export const Layout: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
  const [isDark, setIsDark] = useState(document.documentElement.classList.contains('dark'));
  const location = useLocation();
  const navigate = useNavigate();
  const [currentUser, setCurrentUser] = useState<User | null>(null);

  // Search State
  const [searchQuery, setSearchQuery] = useState('');
  const [searchResults, setSearchResults] = useState<{ members: User[], teams: any[], attendances: any[] }>({ members: [], teams: [], attendances: [] });
  const [isSearching, setIsSearching] = useState(false);
  const [showSearchResults, setShowSearchResults] = useState(false);

  useEffect(() => {
    const delayDebounceFn = setTimeout(async () => {
      if (searchQuery.length >= 2) {
        setIsSearching(true);
        const results = await searchGlobal(searchQuery);
        setSearchResults(results);
        setIsSearching(false);
        setShowSearchResults(true);
      } else {
        setSearchResults({ members: [], teams: [], attendances: [] });
        setShowSearchResults(false);
      }
    }, 300);

    return () => clearTimeout(delayDebounceFn);
  }, [searchQuery]);

  useEffect(() => {
    const fetchCurrentUser = async () => {
      const storedUserId = localStorage.getItem('ctms_user_id');
      if (!storedUserId) {
        navigate('/login');
        return;
      }

      try {
        const user = await getUserById(storedUserId);
        if (user) {
          setCurrentUser(user);
        } else {
          navigate('/login');
        }
      } catch (err) {
        console.error("Layout fetch failed:", err);
      }
    };
    fetchCurrentUser();
  }, [navigate]);

  const handleLogout = () => {
    logout();
    navigate('/login');
  };

  const toggleDarkMode = () => {
    const newDark = !isDark;
    setIsDark(newDark);
    if (newDark) {
      document.documentElement.classList.add('dark');
      document.cookie = "dark_mode=1; path=/; max-age=31536000";
    } else {
      document.documentElement.classList.remove('dark');
      document.cookie = "dark_mode=0; path=/; max-age=31536000";
    }
  };

  // Simple title mapping based on route
  const getPageTitle = () => {
    if (location.pathname === '/') return 'Dashboard';
    if (location.pathname.includes('/admin/users')) return 'Membros';
    if (location.pathname.includes('/admin/teams')) return 'Times';
    if (location.pathname.includes('/users/')) return 'Histórico do Usuário';
    if (location.pathname.includes('/attendances')) return 'Detalhes do Atendimento';
    if (location.pathname.includes('/super-admin')) return 'Gestão de Organizações';
    if (location.pathname.includes('/profile')) return 'Meu Perfil';
    return 'CTMS';
  };

  if (!currentUser) return null;

  const isSuperAdmin = currentUser.role === 'super_admin';

  return (
    <div className="flex h-screen bg-zinc-50 dark:bg-dark-bg overflow-hidden transition-colors duration-300">
      {/* Sidebar */}
      <aside
        className={`fixed inset-y-0 left-0 z-50 w-64 bg-white dark:bg-dark-sidebar border-r border-zinc-200 dark:border-dark-border transform transition-transform duration-300 ease-in-out lg:relative lg:translate-x-0 ${
          isMobileMenuOpen ? 'translate-x-0' : '-translate-x-full'
        }`}
      >
        <div className="flex flex-col h-full">
          {/* Logo */}
          <div className="flex items-center gap-3 px-6 h-20 border-b border-zinc-100 dark:border-dark-border">
            <div className="bg-zinc-900 dark:bg-brand-yellow text-white dark:text-zinc-950 p-2 rounded-lg transition-colors">
              <Hexagon size={24} fill="currentColor" />
            </div>
            <span className="text-xl font-bold text-zinc-900 dark:text-white tracking-tight">Fasto<span className="text-brand-yellow">.</span></span>
            <button onClick={() => setIsMobileMenuOpen(false)} className="ml-auto lg:hidden text-zinc-400">
              <X size={24} />
            </button>
          </div>

          {/* Navigation */}
          <nav className="flex-1 px-4 py-6 space-y-2">
            
            {/* Standard User Links */}
            {!isSuperAdmin && (
              <>
                <SidebarItem to="/" icon={LayoutDashboard} label="Dashboard" collapsed={false} />
                {currentUser.role !== 'agent' && (
                  <>
                    <SidebarItem to="/admin/users" icon={Users} label="Membros" collapsed={false} />
                    <SidebarItem to="/admin/teams" icon={Building2} label={currentUser.role === 'manager' ? 'Meu Time' : 'Times'} collapsed={false} />
                  </>
                )}
              </>
            )}

            {/* Super Admin Links */}
            {isSuperAdmin && (
              <>
                <div className="pt-2 pb-2 px-4 text-xs font-semibold text-zinc-400 dark:text-dark-muted uppercase tracking-wider">
                   Super Admin
                </div>
                <SidebarItem to="/super-admin" icon={Building2} label="Organizações" collapsed={false} />
                <SidebarItem to="/admin/users" icon={Users} label="Usuários Globais" collapsed={false} />
              </>
            )}
          </nav>

          {/* User Profile Mini - Now Clickable to Profile */}
          <div className="p-4 border-t border-zinc-100 dark:border-dark-border">
            <div className="flex items-center gap-3 p-2 rounded-lg bg-zinc-50 dark:bg-dark-bg/50 border border-zinc-100 dark:border-dark-border group">
              <div 
                onClick={() => navigate('/profile')}
                className="flex items-center gap-3 flex-1 min-w-0 cursor-pointer hover:opacity-80 transition-opacity"
              >
                <img 
                  src={currentUser.avatar_url 
                    ? (currentUser.avatar_url.startsWith('http') ? currentUser.avatar_url : `${import.meta.env.PROD ? '' : 'http://localhost:3001'}${currentUser.avatar_url}`)
                    : `https://ui-avatars.com/api/?name=${encodeURIComponent(currentUser.name)}&background=random`} 
                  alt={currentUser.name} 
                  className="w-10 h-10 rounded-full object-cover border border-zinc-200 dark:border-dark-border" 
                />
                <div className="flex-1 min-w-0">
                  <p className="text-sm font-semibold text-zinc-900 dark:text-dark-text truncate">{currentUser.name}</p>
                  <p className="text-xs text-zinc-500 dark:text-dark-muted truncate capitalize">
                    {currentUser.role === 'super_admin' ? 'Super Admin' : 
                     currentUser.role === 'admin' ? 'Administrador' :
                     currentUser.role === 'manager' ? 'Gerente' : 'Agente'}
                  </p>
                </div>
              </div>
              <button 
                onClick={handleLogout}
                className="text-zinc-400 hover:text-red-500 transition-colors shrink-0"
                title="Sair"
              >
                <LogOut size={18} />
              </button>
            </div>
          </div>
        </div>
      </aside>

      {/* Main Content */}
      <div className="flex-1 flex flex-col min-w-0">
        {/* Header */}
        <header className="h-20 bg-white dark:bg-dark-header border-b border-zinc-200 dark:border-dark-border px-4 sm:px-8 flex items-center gap-4 sm:gap-8 z-10 sticky top-0 transition-colors">
          <div className="flex items-center gap-4 shrink-0">
            <button onClick={() => setIsMobileMenuOpen(true)} className="lg:hidden text-zinc-500 hover:text-zinc-900 dark:hover:text-white">
              <Menu size={24} />
            </button>
          </div>

          {/* Search Bar - Moved to left/center and made wider */}
          <div className="hidden md:block relative flex-1 max-w-2xl">
            <div className="flex items-center bg-zinc-100 dark:bg-dark-bg rounded-xl px-4 py-2.5 w-full border border-transparent focus-within:bg-white dark:focus-within:bg-dark-card focus-within:border-brand-yellow focus-within:ring-2 focus-within:ring-brand-yellow/20 dark:focus-within:ring-brand-yellow/10 transition-all">
              {isSearching ? <Loader2 size={18} className="text-brand-yellow animate-spin" /> : <Search size={18} className="text-zinc-400 dark:text-dark-muted" />}
              <input 
                type="text" 
                placeholder="Buscar membros, equipes ou atendimentos..." 
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                onFocus={() => searchQuery.length >= 2 && setShowSearchResults(true)}
                className="bg-transparent border-none outline-none text-sm ml-3 w-full text-zinc-700 dark:text-dark-text placeholder-zinc-400 dark:placeholder-dark-muted" 
              />
            </div>

            {/* Search Results Dropdown */}
            {showSearchResults && (
              <div className="absolute top-full mt-2 left-0 w-full bg-white dark:bg-dark-card border border-zinc-200 dark:border-dark-border rounded-2xl shadow-2xl overflow-hidden z-50 animate-in fade-in slide-in-from-top-2 duration-200">
                <div className="max-h-[480px] overflow-y-auto p-2">
                  {/* Members Section */}
                  {searchResults.members.length > 0 && (
                    <div className="mb-4">
                      <div className="px-3 py-2 text-[10px] font-bold text-zinc-400 dark:text-dark-muted uppercase tracking-widest border-b border-zinc-50 dark:border-dark-border/50 mb-1">Membros</div>
                      {searchResults.members.map(m => (
                        <button
                          key={m.id}
                          onClick={() => {
                            navigate(`/users/${m.slug || m.id}`);
                            setShowSearchResults(false);
                            setSearchQuery('');
                          }}
                          className="w-full flex items-center gap-3 p-2 hover:bg-zinc-50 dark:hover:bg-dark-border rounded-xl transition-colors text-left"
                        >
                          <img 
                            src={m.avatar_url?.startsWith('http') ? m.avatar_url : `${import.meta.env.PROD ? '' : 'http://localhost:3001'}${m.avatar_url || ''}`} 
                            alt={m.name} 
                            className="w-9 h-9 rounded-full border border-zinc-100 dark:border-dark-border object-cover"
                            onError={(e) => { (e.target as HTMLImageElement).src = `https://ui-avatars.com/api/?name=${encodeURIComponent(m.name)}&background=random`; }}
                          />
                          <div>
                            <div className="text-sm font-semibold text-zinc-900 dark:text-dark-text">{m.name}</div>
                            <div className="text-xs text-zinc-500 dark:text-dark-muted">{m.email}</div>
                          </div>
                        </button>
                      ))}
                    </div>
                  )}

                  {/* Teams Section */}
                  {searchResults.teams.length > 0 && (
                    <div className="mb-4">
                      <div className="px-3 py-2 text-[10px] font-bold text-zinc-400 dark:text-dark-muted uppercase tracking-widest border-b border-zinc-50 dark:border-dark-border/50 mb-1">Equipes</div>
                      {searchResults.teams.map(t => (
                        <button
                          key={t.id}
                          onClick={() => {
                            navigate(`/admin/teams`);
                            setShowSearchResults(false);
                            setSearchQuery('');
                          }}
                          className="w-full flex items-center gap-3 p-2 hover:bg-zinc-50 dark:hover:bg-dark-border rounded-xl transition-colors text-left"
                        >
                          <div className="w-9 h-9 rounded-lg bg-zinc-100 dark:bg-dark-bg flex items-center justify-center text-zinc-500 dark:text-dark-muted border border-zinc-200 dark:border-dark-border">
                            <Building2 size={18} />
                          </div>
                          <div>
                            <div className="text-sm font-semibold text-zinc-900 dark:text-dark-text">{t.name}</div>
                            <div className="text-xs text-zinc-500 dark:text-dark-muted line-clamp-1">{t.description || 'Sem descrição'}</div>
                          </div>
                        </button>
                      ))}
                    </div>
                  )}

                  {/* Attendances Section */}
                  {searchResults.attendances.length > 0 && (
                    <div className="mb-2">
                      <div className="px-3 py-2 text-[10px] font-bold text-zinc-400 dark:text-dark-muted uppercase tracking-widest border-b border-zinc-50 dark:border-dark-border/50 mb-1">Atendimentos</div>
                      {searchResults.attendances.map(a => (
                        <button
                          key={a.id}
                          onClick={() => {
                            navigate(`/attendances/${a.id}`);
                            setShowSearchResults(false);
                            setSearchQuery('');
                          }}
                          className="w-full flex items-center gap-3 p-2 hover:bg-zinc-50 dark:hover:bg-dark-border rounded-xl transition-colors text-left"
                        >
                          <div className="w-9 h-9 rounded-lg bg-zinc-100 dark:bg-dark-bg flex items-center justify-center text-zinc-500 dark:text-dark-muted text-[10px] font-bold border border-zinc-200 dark:border-dark-border">
                            KPI
                          </div>
                          <div className="flex-1 min-w-0">
                            <div className="text-sm font-semibold text-zinc-900 dark:text-dark-text truncate">{a.summary}</div>
                            <div className="text-[10px] text-zinc-500 dark:text-dark-muted flex justify-between mt-0.5">
                              <span className="font-medium">{a.user_name}</span>
                              <span>{new Date(a.created_at).toLocaleDateString()}</span>
                            </div>
                          </div>
                        </button>
                      ))}
                    </div>
                  )}

                  {searchResults.members.length === 0 && searchResults.teams.length === 0 && searchResults.attendances.length === 0 && (
                    <div className="p-8 text-center text-zinc-500 dark:text-dark-muted text-sm">
                      Nenhum resultado encontrado para "{searchQuery}"
                    </div>
                  )}
                </div>
              </div>
            )}
          </div>

          <div className="flex items-center gap-4 sm:gap-6 ml-auto shrink-0">
            {/* Dark Mode Toggle */}
            <button 
              onClick={toggleDarkMode}
              className="p-2.5 text-zinc-500 dark:text-dark-muted hover:bg-zinc-100 dark:hover:bg-dark-border rounded-xl transition-all"
              title={isDark ? "Mudar para Modo Claro" : "Mudar para Modo Escuro"}
            >
              {isDark ? <Sun size={20} /> : <Moon size={20} />}
            </button>

            {/* Notifications */}
            <div className="relative">
              <button className="p-2 text-zinc-500 dark:text-dark-muted hover:bg-zinc-100 dark:hover:bg-dark-border rounded-full relative transition-colors">
                <Bell size={20} />
                <span className="absolute top-1.5 right-2 w-2.5 h-2.5 bg-brand-yellow rounded-full border-2 border-white dark:border-dark-header"></span>
              </button>
            </div>
          </div>
        </header>

        {/* Scrollable Content Area */}
        <main className="flex-1 overflow-y-auto p-4 sm:p-8">
          {children}
        </main>
      </div>
      
      {/* Overlay for mobile */}
      {isMobileMenuOpen && (
        <div 
          className="fixed inset-0 bg-zinc-950/50 z-40 lg:hidden"
          onClick={() => setIsMobileMenuOpen(false)}
        />
      )}
    </div>
  );
};
