import React, { useState, useEffect } from 'react';
import { NavLink, useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { useAuth } from '../context/AuthContext';
import LanguageSelector from './LanguageSelector';
import Footer from './Footer';
import useFormatters from '../hooks/useFormatters';
import logo from '../assets/logo-white.png';

const Layout = ({ children }) => {
  const navigate = useNavigate();
  const { user, logout } = useAuth();
  const { t, i18n } = useTranslation();
  const { date } = useFormatters();
  
  // Sidebar colapsado por padrão em mobile, expandido em desktop
  const getInitialSidebarState = () => window.innerWidth < 1024;
  const [sidebarCollapsed, setSidebarCollapsed] = useState(getInitialSidebarState);
  
  // Atualizar estado do sidebar quando a tela for redimensionada
  useEffect(() => {
    const handleResize = () => {
      const isMobile = window.innerWidth < 1024;
      setSidebarCollapsed(isMobile);
    };
    
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);
  
  const [expandedGroups, setExpandedGroups] = useState({
    movements: true,
    planning: true,
    settings: false,
  });

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

  const toggleGroup = (group) => {
    setExpandedGroups(prev => ({
      ...prev,
      [group]: !prev[group]
    }));
  };

  // Menu organizado com grupos
  const menuStructure = [
    { type: 'item', path: '/dashboard', icon: 'bi-speedometer2', label: t('nav.dashboard') },
    { type: 'item', path: '/accounts', icon: 'bi-wallet2', label: t('nav.accounts') },
    { 
      type: 'group', 
      id: 'movements',
      icon: 'bi-arrow-left-right', 
      label: t('nav.movements'),
      items: [
        { path: '/transactions', icon: 'bi-receipt', label: t('nav.transactions') },
        { path: '/recurring', icon: 'bi-calendar-check', label: t('recurring.title') },
        { path: '/import', icon: 'bi-file-earmark-arrow-up', label: t('nav.import') },
        { path: '/transfers', icon: 'bi-arrow-repeat', label: t('nav.transfers') },
        { path: '/refunds', icon: 'bi-receipt-cutoff', label: t('nav.refunds') },
      ]
    },
    { type: 'item', path: '/liabilities', icon: 'bi-bank', label: t('nav.liabilities') },
    { type: 'item', path: '/business', icon: 'bi-briefcase', label: t('nav.business') },
    { 
      type: 'group', 
      id: 'planning',
      icon: 'bi-graph-up', 
      label: t('nav.planning'),
      items: [
        { path: '/financial-health', icon: 'bi-heart-pulse', label: t('nav.financialHealth') },
        { path: '/goals', icon: 'bi-flag', label: t('nav.goals') },
        { path: '/budgets', icon: 'bi-wallet2', label: t('nav.budgets') },
        { path: '/reports', icon: 'bi-bar-chart-line', label: t('nav.reports') },
      ]
    },
    { 
      type: 'group', 
      id: 'settings',
      icon: 'bi-gear', 
      label: t('nav.settings'),
      items: [
        { path: '/categories', icon: 'bi-tags', label: t('nav.categories') },
        { path: '/cost-centers', icon: 'bi-building', label: t('nav.costCenters') },
      ]
    },
  ];

  // Formata data de acordo com o idioma
  const formatDate = () => {
    const now = new Date();
    const locale = i18n.language === 'pt-BR' ? 'pt-BR' : 
                   i18n.language === 'en' ? 'en-US' : 'es-ES';
    return now.toLocaleDateString(locale, { 
      weekday: 'long', 
      year: 'numeric', 
      month: 'long', 
      day: 'numeric' 
    });
  };

  return (
    <div className="app-layout">
      {/* Sidebar */}
      <aside className={`app-sidebar ${sidebarCollapsed ? 'collapsed' : ''}`}>
        {/* Logo Section */}
        <div className="sidebar-logo">
          <div className="logo-content">
            {!sidebarCollapsed && (
              <div className="logo-brand">
                <img src={logo} alt="WebMoney" className="logo-image" style={{ height: '40px', width: 'auto' }} />
                <span className="logo-text">WebMoney</span>
              </div>
            )}
            <button 
              className="sidebar-toggle"
              onClick={() => setSidebarCollapsed(!sidebarCollapsed)}
              title={sidebarCollapsed ? t('categories.expand') : t('categories.collapse')}
            >
              <i className={`bi ${sidebarCollapsed ? 'bi-chevron-right' : 'bi-chevron-left'}`}></i>
            </button>
          </div>
        </div>

        {/* Navigation */}
        <nav className="sidebar-nav">
          {menuStructure.map((item) => (
            item.type === 'group' ? (
              <div key={item.id} className="sidebar-group">
                <button
                  className={`sidebar-group-toggle ${expandedGroups[item.id] ? 'expanded' : ''}`}
                  onClick={() => !sidebarCollapsed && toggleGroup(item.id)}
                  title={sidebarCollapsed ? item.label : ''}
                >
                  <span className="sidebar-link-icon">
                    <i className={`bi ${item.icon}`}></i>
                  </span>
                  {!sidebarCollapsed && (
                    <>
                      <span className="sidebar-link-text">{item.label}</span>
                      <i className={`bi bi-chevron-${expandedGroups[item.id] ? 'up' : 'down'} sidebar-group-arrow`}></i>
                    </>
                  )}
                </button>
                {!sidebarCollapsed && expandedGroups[item.id] && (
                  <div className="sidebar-group-items">
                    {item.items.map((subItem) => (
                      <NavLink
                        key={subItem.path}
                        to={subItem.path}
                        className={({ isActive }) => `sidebar-link sidebar-sublink ${isActive ? 'active' : ''}`}
                      >
                        <span className="sidebar-link-icon">
                          <i className={`bi ${subItem.icon}`}></i>
                        </span>
                        <span className="sidebar-link-text">{subItem.label}</span>
                      </NavLink>
                    ))}
                  </div>
                )}
                {sidebarCollapsed && (
                  <div className="sidebar-collapsed-submenu">
                    {item.items.map((subItem) => (
                      <NavLink
                        key={subItem.path}
                        to={subItem.path}
                        className={({ isActive }) => `sidebar-link ${isActive ? 'active' : ''}`}
                        title={subItem.label}
                      >
                        <span className="sidebar-link-icon">
                          <i className={`bi ${subItem.icon}`}></i>
                        </span>
                      </NavLink>
                    ))}
                  </div>
                )}
              </div>
            ) : (
              <NavLink
                key={item.path}
                to={item.path}
                className={({ isActive }) => `sidebar-link ${isActive ? 'active' : ''}`}
                title={sidebarCollapsed ? item.label : ''}
              >
                <span className="sidebar-link-icon">
                  <i className={`bi ${item.icon}`}></i>
                </span>
                {!sidebarCollapsed && <span className="sidebar-link-text">{item.label}</span>}
              </NavLink>
            )
          ))}
        </nav>

        {/* User Section */}
        <div className="sidebar-user">
          {!sidebarCollapsed ? (
            <div className="user-info">
              <div className="user-avatar">
                <i className="bi bi-person-fill"></i>
              </div>
              <div className="user-details">
                <div className="user-name">{user?.name}</div>
                <div className="user-email">{user?.email}</div>
              </div>
              <button 
                onClick={handleLogout} 
                className="user-logout"
                title={t('auth.logout')}
              >
                <i className="bi bi-box-arrow-right"></i>
              </button>
            </div>
          ) : (
            <button 
              onClick={handleLogout} 
              className="user-logout-collapsed"
              title={t('auth.logout')}
            >
              <i className="bi bi-box-arrow-right"></i>
            </button>
          )}
        </div>
      </aside>

      {/* Main Content */}
      <main className={`app-main ${sidebarCollapsed ? 'expanded' : ''}`}>
        {/* Top Bar */}
        <header className="app-header">
          <div className="header-welcome">
            <span className="welcome-label">{t('dashboard.welcome')},</span>
            <span className="welcome-name">{user?.name}</span>
          </div>
          <div className="header-actions">
            <LanguageSelector variant="dropdown" />
            <div className="header-date">
              <i className="bi bi-calendar3"></i>
              <span>{formatDate()}</span>
            </div>
          </div>
        </header>

        {/* Page Content */}
        <div className="app-content">
          {children}
        </div>

        {/* Footer */}
        <Footer />
      </main>
    </div>
  );
};

export default Layout;
