import React from 'react';
import { motion } from 'framer-motion';
import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/button';
import { LogOut, Bell, Settings, Menu, Building } from 'lucide-react';

import { useDocumentMetadata } from '@/hooks/useDocumentMetadata';

/**
 * @typedef {Object} AppLayoutProps
 * @property {React.ReactNode} children - Conteúdo principal
 * @property {React.ReactNode} sidebar - Componente de navegação lateral
 * @property {string} title - Título da página
 * @property {string} [userName] - Nome do usuário ativo
 * @property {() => void} [onLogout] - Função de callback para logout
 * @property {string} [headerClassName] - Classe customizada para o header
 * @property {string} [sidebarClassName] - Classe customizada para a sidebar
 * @property {string} [subtitle] - Subtítulo da página
 * @property {React.ReactNode} [headerExtras] - Elementos extras para o header (ex: ticker)
 * @property {string} [contentClassName] - Classe customizada para o container de conteúdo
 * @property {React.ElementType} [brandIcon] - Ícone da marca
 * @property {React.ReactNode} [brandName] - Nome da marca
 * @property {string} [brandColorClass] - Classe de cor para o ícone
 * @property {'fleet' | 'finance' | 'rh'} [metadataType] - Tipo de ambiente para o favicon e metadados
 */

/**
 * Layout principal modular do sistema.
 * @param {AppLayoutProps} props
 */
export const AppLayout = ({ 
  children, 
  sidebar, 
  title, 
  subtitle,
  userName = 'Administrador', 
  onLogout,
  headerClassName,
  sidebarClassName,
  headerExtras,
  contentClassName,
  brandIcon: BrandIcon = Building,
  brandName = 'Integra',
  brandColorClass = 'bg-primary shadow-primary/20',
  metadataType
}) => {
  const [isSidebarOpen, setIsSidebarOpen] = React.useState(true);

  // Define o nome da aba como o nome da marca (Ex: Pralog Frota)
  const tabTitle = typeof brandName === 'string' ? brandName : 'Integra Platform';
  useDocumentMetadata(tabTitle, metadataType);

  return (
    <div className="flex h-screen bg-slate-50 overflow-hidden font-inter text-slate-700">
      {/* Sidebar Desktop */}
      <aside 
        className={cn(
          "bg-white border-r border-slate-100 transition-all duration-300 flex flex-col z-20 shadow-sm",
          sidebarClassName,
          isSidebarOpen ? "w-64" : "w-0 -translate-x-full md:w-20 md:translate-x-0"
        )}
      >
        <div className="p-6 h-20 border-b border-slate-100 flex items-center justify-between overflow-hidden whitespace-nowrap group">
          <div className="flex items-center gap-3">
             <div className={cn("w-10 h-10 rounded-xl flex items-center justify-center shrink-0 shadow-lg group-hover:scale-105 transition-transform duration-300", brandColorClass)}>
               <BrandIcon size={22} className="text-white" strokeWidth={2.5} />
             </div>
             {isSidebarOpen && <span className="font-bold text-2xl tracking-tighter text-slate-900">{brandName}</span>}
          </div>
          <Button variant="ghost" size="icon" onClick={() => setIsSidebarOpen(!isSidebarOpen)} className="md:flex hidden text-slate-400 hover:text-slate-900 hover:bg-slate-50">
            <Menu size={20} />
          </Button>
        </div>
        
        <div className="flex-1 overflow-y-auto overflow-x-hidden p-4">
          {React.isValidElement(sidebar) 
            ? React.cloneElement(sidebar, { isCollapsed: !isSidebarOpen }) 
            : sidebar}
        </div>

        <div className="p-4 border-t overflow-hidden border-slate-100">
           <Button variant="ghost" className="w-full justify-start gap-3 text-slate-400 hover:text-rose-600 hover:bg-rose-50 transition-colors" onClick={onLogout}>
             <LogOut size={20} />
             {isSidebarOpen && <span>Sair</span>}
           </Button>
        </div>
      </aside>

      {/* Main Content */}
      <main className={cn("flex-1 flex flex-col relative overflow-hidden bg-slate-50", contentClassName)}>
        {/* Header */}
        <header className={cn(
          "h-20 border-b border-slate-100 bg-white/80 backdrop-blur-md flex items-center justify-between px-8 sticky top-0 z-10",
          headerClassName
        )}>
          <div className="flex items-center gap-4">
            <Button variant="ghost" size="icon" onClick={() => setIsSidebarOpen(!isSidebarOpen)} className="md:hidden text-slate-400">
              <Menu size={20} />
            </Button>
            <div className="flex flex-col">
              <h1 className="text-base font-bold text-slate-900 leading-tight">{title}</h1>
              {subtitle && <p className="text-[11px] text-slate-500 font-bold uppercase tracking-widest">{subtitle}</p>}
            </div>
          </div>
          
          <div className="flex items-center gap-6">
            {headerExtras}
            
            <div className="flex items-center gap-2">
              <div className="flex items-center gap-3 ml-2 border-l border-slate-100 pl-6">
                 <div className="w-10 h-10 rounded-full bg-emerald-500/10 border border-emerald-500/10 flex items-center justify-center text-emerald-600 font-black text-xs shadow-inner">
                   {userName.substring(0, 2).toUpperCase()}
                 </div>
              </div>
            </div>
          </div>
        </header>

        {/* Dynamic Content */}
        <section className="flex-1 overflow-auto p-4 md:p-6">
          <motion.div
            initial={{ opacity: 0, y: 10 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.3 }}
          >
            {children}
          </motion.div>
        </section>
      </main>
    </div>
  );
};
