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 } from 'lucide-react';
import { USERS } from '../constants';
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-yellow-400 text-slate-900 font-semibold shadow-md shadow-yellow-400/20'
          : 'text-slate-500 hover:bg-slate-100 hover:text-slate-900'
      }`
    }
  >
    <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 location = useLocation();
  const navigate = useNavigate();
  const [currentUser, setCurrentUser] = useState<User>(USERS[1]); // Default to standard user fallback

  useEffect(() => {
    const storedUserId = localStorage.getItem('ctms_user_id');
    if (storedUserId) {
      const user = USERS.find(u => u.id === storedUserId);
      if (user) {
        setCurrentUser(user);
      }
    }
  }, []);

  const handleLogout = () => {
    localStorage.removeItem('ctms_user_id');
    navigate('/login');
  };

  // Simple title mapping based on route
  const getPageTitle = () => {
    if (location.pathname === '/') return 'Dashboard';
    if (location.pathname.includes('/admin/users')) return 'Gestão de Equipe';
    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';
  };

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

  return (
    <div className="flex h-screen bg-slate-50 overflow-hidden">
      {/* Sidebar */}
      <aside
        className={`fixed inset-y-0 left-0 z-50 w-64 bg-white border-r border-slate-200 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-slate-100">
            <div className="bg-slate-900 text-white p-2 rounded-lg">
              <Hexagon size={24} fill="currentColor" />
            </div>
            <span className="text-xl font-bold text-slate-900 tracking-tight">Fasto<span className="text-yellow-500">.</span></span>
            <button onClick={() => setIsMobileMenuOpen(false)} className="ml-auto lg:hidden text-slate-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="Equipe" collapsed={false} />
              </>
            )}

            {/* Super Admin Links */}
            {isSuperAdmin && (
              <>
                <div className="pt-2 pb-2 px-4 text-xs font-semibold text-slate-400 uppercase tracking-wider">
                   Super Admin
                </div>
                <SidebarItem to="/super-admin" icon={Building2} label="Organizações" collapsed={false} />
              </>
            )}

            <div className="pt-4 pb-2 px-4 text-xs font-semibold text-slate-400 uppercase tracking-wider">
              Sistema
            </div>
            <SidebarItem to="/profile" icon={UserCircle} label="Perfil" collapsed={false} />
          </nav>

          {/* User Profile Mini */}
          <div className="p-4 border-t border-slate-100">
            <div className="flex items-center gap-3 p-2 rounded-lg bg-slate-50 border border-slate-100">
              <img src={currentUser.avatar_url} alt="User" className="w-10 h-10 rounded-full object-cover" />
              <div className="flex-1 min-w-0">
                <p className="text-sm font-semibold text-slate-900 truncate">{currentUser.name}</p>
                <p className="text-xs text-slate-500 truncate capitalize">{currentUser.role === 'super_admin' ? 'Super Admin' : currentUser.role}</p>
              </div>
              <button 
                onClick={handleLogout}
                className="text-slate-400 hover:text-red-500 transition-colors"
                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 border-b border-slate-200 px-4 sm:px-8 flex items-center justify-between z-10 sticky top-0">
          <div className="flex items-center gap-4">
            <button onClick={() => setIsMobileMenuOpen(true)} className="lg:hidden text-slate-500 hover:text-slate-900">
              <Menu size={24} />
            </button>
            <h1 className="text-xl font-bold text-slate-800 hidden sm:block">{getPageTitle()}</h1>
          </div>

          <div className="flex items-center gap-4 sm:gap-6">
            {/* Search Bar */}
            <div className="hidden md:flex items-center bg-slate-100 rounded-full px-4 py-2 w-64 border border-transparent focus-within:bg-white focus-within:border-yellow-400 focus-within:ring-2 focus-within:ring-yellow-100 transition-all">
              <Search size={18} className="text-slate-400" />
              <input 
                type="text" 
                placeholder="Buscar..." 
                className="bg-transparent border-none outline-none text-sm ml-2 w-full text-slate-700 placeholder-slate-400" 
              />
            </div>

            {/* Notifications */}
            <div className="relative">
              <button className="p-2 text-slate-500 hover:bg-slate-100 rounded-full relative transition-colors">
                <Bell size={20} />
                <span className="absolute top-1.5 right-2 w-2.5 h-2.5 bg-yellow-400 rounded-full border-2 border-white"></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-slate-900/50 z-40 lg:hidden"
          onClick={() => setIsMobileMenuOpen(false)}
        />
      )}
    </div>
  );
};