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 
} from 'lucide-react';
import { getAttendances, getUsers, getUserById, logout } 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);

  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} />
                <SidebarItem to="/admin/users" icon={Users} label="Membros" collapsed={false} />
                <SidebarItem to="/admin/teams" icon={Building2} label="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 justify-between z-10 sticky top-0 transition-colors">
          <div className="flex items-center gap-4">
            <button onClick={() => setIsMobileMenuOpen(true)} className="lg:hidden text-zinc-500 hover:text-zinc-900 dark:hover:text-white">
              <Menu size={24} />
            </button>
            <h1 className="text-xl font-bold text-zinc-800 dark:text-dark-text hidden sm:block">{getPageTitle()}</h1>
          </div>

          <div className="flex items-center gap-4 sm:gap-6">
            {/* 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>

            {/* Search Bar */}
            <div className="hidden md:flex items-center bg-zinc-100 dark:bg-dark-bg rounded-full px-4 py-2 w-64 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">
              <Search size={18} className="text-zinc-400 dark:text-dark-muted" />
              <input 
                type="text" 
                placeholder="Buscar..." 
                className="bg-transparent border-none outline-none text-sm ml-2 w-full text-zinc-700 dark:text-dark-text placeholder-zinc-400 dark:placeholder-dark-muted" 
              />
            </div>

            {/* 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>
  );
};
