import { Component, OnInit, Output, EventEmitter, OnDestroy } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { Router, RouterLink, RouterLinkActive } from '@angular/router';
import { MobileMenuService } from '../../services/mobile-menu.service';
import { ThemeService } from '../../services/theme.service';
import { Subscription } from 'rxjs';

interface MenuItem {
  id: string;
  label: string;
  icon: string;
  notifications: number;
  children?: MenuItem[];
  expanded?: boolean;
}

@Component({
  selector: 'app-sidebar',
  standalone: true,
  imports: [CommonModule, FormsModule, RouterLink, RouterLinkActive],
  template: `
    <aside class="sidebar" 
           [class.collapsed]="isCollapsed"
           [class.hidden-mobile]="isHiddenInMobile">
      <div class="search-container">
        <div class="search-input-group">
          <i class="fas fa-search search-icon"></i>
          <input 
            type="text" 
            [(ngModel)]="searchTerm" 
            placeholder="Buscar..."
            (input)="filterMenuItems()"
            class="search-input"
          >
          <button class="toggle-btn" (click)="toggleSidebar()" title="Recolher sidebar">
            <i class="fas fa-chevron-left" [class.rotated]="isCollapsed"></i>
          </button>
        </div>
      </div>

      <nav class="menu">
        <ul>
          <ng-container *ngFor="let item of filteredMenuItems">
            <!-- Item principal -->
            <li [class.active]="selectedItem === item.id"
                [class.has-children]="item.children && item.children.length > 0"
                [class.expanded]="item.expanded">
              
              <div class="menu-item" 
                   (click)="selectMenuItem(item)"
                   [routerLink]="!item.children ? ['/app', item.id] : null"
                   routerLinkActive="active"
                   [routerLinkActiveOptions]="{exact: true}">
                <i [class]="item.icon"></i>
                <span class="menu-text">{{ item.label }}</span>
                <span class="notification" *ngIf="item.notifications > 0">
                  {{ item.notifications }}
                </span>
                <i class="expand-icon fas fa-chevron-down" 
                   *ngIf="item.children && item.children.length > 0 && !isCollapsed"
                   [class.rotated]="item.expanded"></i>
              </div>

              <!-- Submenus -->
              <ul class="submenu" *ngIf="item.children && item.expanded && !isCollapsed">
                <li *ngFor="let child of item.children"
                    [class.active]="selectedItem === child.id"
                    routerLinkActive="active"
                    [routerLinkActiveOptions]="{exact: true}"
                    (click)="selectMenuItem(child)"
                    [routerLink]="['/app', child.id]">
                  <div class="submenu-item">
                    <i [class]="child.icon"></i>
                    <span class="menu-text">{{ child.label }}</span>
                    <span class="notification" *ngIf="child.notifications > 0">
                      {{ child.notifications }}
                    </span>
                  </div>
                </li>
              </ul>
            </li>
          </ng-container>
        </ul>
      </nav>

      <div class="license-info">
        <div class="license-content">
          <div class="company-name">Grupo PRA</div>
          <div class="cnpj">CNPJ: 31.882.636/0001-38</div>
        </div>
        <div class="version-info">
          <span>Versão 1.0.0</span>
        </div>
      </div>
    </aside>
  `,
  styles: [`
    .sidebar {
      width: 240px;
      height: 100%;
      background: var(--sidebar-bg);
      color: var(--text-primary);
      box-shadow: 2px 0 8px rgba(0,0,0,0.1);
      display: flex;
      flex-direction: column;
      transition: all 0.3s ease;
      position: relative;
      border-right: 1px solid var(--divider);
      z-index: 1000;
      margin-left: 8px; /* ✨ Efeito de flutuação no desktop */
      border-radius: 0 8px 8px 0; /* Bordas arredondadas para reforçar o efeito */
    }

    .sidebar.collapsed {
      width: 80px;
      margin-left: 8px; /* Manter efeito de flutuação quando collapsed */
    }

    .sidebar.hidden-mobile {
      transform: translateX(-100%);
      opacity: 0;
      pointer-events: none;
    }

    .sidebar.mobile-overlay::before {
      content: '';
      position: fixed;
      top: 0;
      left: 0;
      width: 100vw;
      height: 100vh;
      background: rgba(0, 0, 0, 0.5);
      z-index: -1;
      opacity: 1;
      transition: opacity 0.3s ease;
    }

    .search-container {
      padding: 1rem;
      border-bottom: 1px solid #f0f0f0;
    }

    .search-input-group {
      position: relative;
      display: flex;
      align-items: center;
      background: var(--surface);
      border: 1px solid var(--divider);
      border-radius: 8px;
      transition: all 0.2s ease;
      overflow: hidden;
    }

    .search-input-group:focus-within {
      border-color: var(--primary);
      box-shadow: 0 0 0 2px rgba(241, 196, 15, 0.1);
    }

    .search-icon {
      padding: 0 0.75rem;
      color: #666;
      font-size: 0.9rem;
    }

    .search-input {
      flex: 1;
      border: none;
      outline: none;
      padding: 0.75rem 0;
      background: transparent;
      color: var(--text-primary);
      font-size: 0.9rem;
    }

    .search-input::placeholder {
      color: #999;
    }

    .toggle-btn {
      background: none;
      border: none;
      color: #666;
      cursor: pointer;
      padding: 0.75rem;
      transition: all 0.2s ease;
      border-left: 1px solid var(--divider);
    }

    .toggle-btn:hover {
      background: rgba(241, 196, 15, 0.1);
      color: var(--primary);
    }

    .toggle-btn i {
      transition: transform 0.3s ease;
      font-size: 0.9rem;
    }

    .toggle-btn i.rotated {
      transform: rotate(180deg);
    }

    .menu {
      flex: 1;
      overflow-y: auto;
      padding: 1rem 0;
    }

    .menu ul {
      list-style: none;
      padding: 0;
      margin: 0;
    }

    .menu > ul > li {
      color: var(--text-primary);
      position: relative;
    }

    .menu-item {
      padding: 0.75rem 1.5rem;
      display: flex;
      align-items: center;
      cursor: pointer;
      transition: background-color 0.2s ease;
      position: relative;
    }

    .menu-item:hover {
      color: var(--primary);
    }

    .menu > ul > li.active > .menu-item {
      background-color: #FFC82E;
      color: #8B4513;
      font-weight: 600;
      border-radius: 12px;
      margin: 0 0.75rem;
      border-left: none;
    }

    .menu-item i {
      font-size: 1.25rem;
      width: 24px;
      text-align: center;
      margin-right: 1rem;
    }

    .expand-icon {
      margin-left: auto;
      font-size: 0.875rem;
      transition: transform 0.3s ease;
    }

    .expand-icon.rotated {
      transform: rotate(180deg);
    }

    .collapsed .menu-text {
      display: none;
    }

    .collapsed .expand-icon {
      display: none;
    }

    .collapsed .search-container {
      padding: 0.5rem;
    }

    .collapsed .search-input-group {
      justify-content: center;
    }

    .collapsed .search-icon,
    .collapsed .search-input {
      display: none;
    }

    .collapsed .toggle-btn {
      border-left: none;
      padding: 0.75rem;
    }

    .notification {
      background-color: #ef4444;
      color: white;
      border-radius: 12px;
      padding: 0.25rem 0.5rem;
      font-size: 0.75rem;
      margin-left: auto;
      margin-right: 0.5rem;
    }

    .collapsed .notification {
      margin-right: 0;
    }

    /* Estilos para submenu */
    .submenu {
      background-color: transparent;
      border-left: none;
      margin-left: 0;
      padding: 0.5rem 0;
    }

    .submenu li {
      position: relative;
    }

    .submenu-item {
      padding: 0.5rem 1rem 0.5rem 2.5rem;
      display: flex;
      align-items: center;
      cursor: pointer;
      transition: all 0.2s ease;
      color: var(--text-primary);
      font-size: 0.9rem;
      margin: 0.25rem 0.75rem;
      border-radius: 8px;
    }

    .submenu-item:hover {
      background-color: rgba(255, 200, 46, 0.1);
      color: var(--primary);
    }

    .submenu li.active .submenu-item {
      background-color: #FFC82E;
      color: #8B4513;
      font-weight: 600;
      border-radius: 8px;
    }

    .submenu-item i {
      font-size: 1rem;
      width: 20px;
      text-align: center;
      margin-right: 0.75rem;
    }

    .submenu .notification {
      font-size: 0.7rem;
      padding: 0.125rem 0.375rem;
    }

    .license-info {
      padding: 0.25rem;
      font-size: 0.75rem;
    }

    .license-content {
      padding: 0.5rem;
      border-radius: 4px;
      background: white;
      box-shadow: 
        0 1px 2px rgba(0,0,0,0.1),
        inset 0 1px 2px rgba(255,255,255,0.2);
      position: relative;
      overflow: hidden;
    }

    /* Tema escuro - license content com logo para dark 
    :host-context(.dark-theme) .license-content::before {
      background-image: url('./assets/imagens/logo_for_dark.png');
    } */

    .company-name {
      color: var(--primary);
      font-weight: 600;
      text-align: center;
      margin-bottom: 0.25rem;
      position: relative;
      z-index: 1;
    }

    .cnpj {
      color: #64748b;
      text-align: center;
      font-family: monospace;
      letter-spacing: 0.5px;
      position: relative;
      z-index: 1;
    }

    .version-info {
      text-align: center;
      color: #64748b;
      margin-top: 0.5rem;
      font-size: 0.7rem;
    }

    .collapsed .license-info {
      padding: 0.5rem;
      
      .license-content {
        display: none;
      }
      
      .version-info {
        margin-top: 0;
      }
    }

    /* ✅ MOBILE: Sidebar completamente oculta por padrão */
    @media (max-width: 768px) {
      .sidebar {
        /* Ocultar por padrão em mobile */
        transform: translateX(-100%);
        opacity: 0;
        pointer-events: none;
        width: 240px; /* Largura fixa quando visível */
        background: var(--sidebar-bg);
        /* Sombra mais intensa quando visível em mobile */
        box-shadow: 0 0 20px rgba(0, 0, 0, 0.4);
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        position: fixed;
        top: 60px; /* Posicionamento simples abaixo do header */
        left: 0;
        height: calc(100vh - 60px - 80px); /* Header + footer menu */
        z-index: 1002;
        margin-left: 0; /* Remover margin em mobile para usar largura total */
        border-radius: 0; /* Remover bordas arredondadas em mobile */
      }

      /* Quando forçar visibilidade (através do mobile menu) */
      .sidebar.force-visible {
        transform: translateX(0);
        opacity: 1;
        pointer-events: all;
      }

      /* ✅ Adicionar overlay clicável quando sidebar está visível em mobile */
      .sidebar.force-visible::before {
        content: '';
        position: fixed;
        top: 60px; /* Posicionamento simples abaixo do header */
        left: 240px; /* Começa onde a sidebar termina */
        width: calc(100vw - 240px);
        height: calc(100vh - 60px - 80px); /* Header + footer menu */
        background: rgba(0, 0, 0, 0.6);
        z-index: -1;
        opacity: 1;
        transition: opacity 0.3s ease;
        pointer-events: all;
        cursor: pointer; /* ✅ Indicar que é clicável */
      }

      /* Estados collapsed não se aplicam em mobile - sempre largura fixa */
      .sidebar.collapsed {
        width: 240px;
      }

      /* ✅ Ocultar botão chevron no mobile - controle é feito pelo footer */
      .toggle-btn {
        display: none !important;
      }
      
      /* ✅ SOLUÇÃO SIMPLES: Container de pesquisa super simplificado */
      .search-container {
        padding: 1rem !important;
        border-bottom: 1px solid #f0f0f0 !important;
        background: white !important; /* Fundo branco simples */
      }

      .search-input-group {
        background: white !important;
        border: 2px solid #ddd !important; /* Borda mais visível */
        min-height: 50px !important; /* Altura maior */
        display: block !important; /* Display simples */
        border-radius: 8px !important;
        padding: 0 !important;
        position: relative !important;
      }
      
      .search-icon {
        display: none !important; /* Remover ícone temporariamente */
      }
      
      .search-input {
        font-size: 16px !important;
        padding: 15px !important; /* Padding grande */
        background: white !important;
        color: #333 !important;
        border: none !important;
        outline: none !important;
        width: 100% !important;
        height: 50px !important;
        border-radius: 8px !important;
        box-sizing: border-box !important;
        /* Remover todas as propriedades complexas */
      }
      
      .search-input::placeholder {
        color: #999 !important;
      }

      .collapsed .menu-text {
        display: block; /* Mostrar texto em mobile mesmo quando "collapsed" */
      }

      .collapsed .expand-icon {
        display: inline-block; /* Mostrar ícones de expansão */
      }

      .collapsed .logo {
        width: auto; /* Logo normal em mobile */
      }

      .collapsed .license-info .license-content {
        display: block; /* Mostrar informações da licença */
      }
    }
  `]
})
export class SidebarComponent implements OnInit, OnDestroy {
  @Output() collapsedChange = new EventEmitter<boolean>();
  isCollapsed = false;
  isHiddenInMobile = false;
  isForcedVisible = false;
  searchTerm = '';
  selectedItem: string | null = null;
  private isDarkMode = false;
  private themeSubscription = new Subscription();
  menuItems: MenuItem[] = [
    { id: 'dashboard', label: 'Dashboard', icon: 'fas fa-home', notifications: 0 },
    { id: 'vehicles', label: 'Veículos', icon: 'fas fa-car', notifications: 0 },
    { id: 'drivers', label: 'Motoristas', icon: 'fas fa-user', notifications: 0 },
    { id: 'maintenance', label: 'Manutenção', icon: 'fas fa-wrench', notifications: 0 },
    { 
      id: 'finances', 
      label: 'Finanças', 
      icon: 'fas fa-chart-line', 
      notifications: 0,
      expanded: false,
      children: [
        { id: 'accountpayable', label: 'Contas a Pagar', icon: 'fas fa-file-invoice-dollar', notifications: 0 }
      ]
    },
    { 
      id: 'routes', 
      label: 'Rotas', 
      icon: 'fas fa-route', 
      notifications: 0,
      expanded: false,
      children: [
        { id: 'mercado-live', label: 'Mercado Live', icon: 'fas fa-shopping-cart', notifications: 0 },
        { id: 'shopee', label: 'Shopee', icon: 'fas fa-store', notifications: 0 }
      ]
    },
    { id: 'reports', label: 'Relatórios', icon: 'fas fa-chart-bar', notifications: 0 },
    { id: 'settings', label: 'Configurações', icon: 'fas fa-cog', notifications: 0 },
  ];
  filteredMenuItems: MenuItem[] = [...this.menuItems];
  private mediaQuery: MediaQueryList;
  private mediaQueryListener: ((this: MediaQueryList, ev: MediaQueryListEvent) => any) | null = null;

  constructor(private router: Router, private mobileMenuService: MobileMenuService, private themeService: ThemeService) {
    this.mediaQuery = window.matchMedia('(max-width: 768px)');
    this.isHiddenInMobile = this.mediaQuery.matches;
    this.isCollapsed = this.mediaQuery.matches;
  }

  ngOnInit() {
    // Subscrever ao estado do tema
    this.themeSubscription = this.themeService.isDarkMode$.subscribe(isDark => {
      this.isDarkMode = isDark;
    });

    this.mediaQueryListener = (e: MediaQueryListEvent) => {
      const isMobile = e.matches;
      
      this.isHiddenInMobile = isMobile;
      this.isCollapsed = isMobile;
      
      if (isMobile) {
        this.isForcedVisible = false;
        this.updateSidebarClasses();
        this.mobileMenuService.setSidebarVisible(false);
      }
      
      this.collapsedChange.emit(this.isCollapsed);
    };

    this.mediaQuery.addEventListener('change', this.mediaQueryListener);
    this.selectMenuItem({ id: 'dashboard' } as MenuItem);
    
    this.updateSidebarClasses();

    document.addEventListener('click', this.handleOutsideClick.bind(this));
  }

  ngOnDestroy() {
    // Limpar subscription do tema
    this.themeSubscription.unsubscribe();
    
    if (this.mediaQueryListener) {
      this.mediaQuery.removeEventListener('change', this.mediaQueryListener);
    }
    
    document.removeEventListener('click', this.handleOutsideClick.bind(this));
  }

  private handleOutsideClick(event: Event) {
    const isMobile = this.mediaQuery.matches;
    
    if (isMobile && this.isForcedVisible) {
      const target = event.target as HTMLElement;
      const sidebar = document.querySelector('.sidebar') as HTMLElement;
      const mobileFooterMenu = document.querySelector('.mobile-footer-menu') as HTMLElement;
      
      if (sidebar && !sidebar.contains(target) && 
          mobileFooterMenu && !mobileFooterMenu.contains(target)) {
        this.hideMobileSidebar();
      }
    }
  }

  toggleSidebar() {
    const isMobile = this.mediaQuery.matches;
    
    if (isMobile) {
      this.isForcedVisible = !this.isForcedVisible;
      this.updateSidebarClasses();
      this.mobileMenuService.setSidebarVisible(this.isForcedVisible);
      console.log('📱 Mobile sidebar toggled:', this.isForcedVisible ? 'visible' : 'hidden');
    } else {
      this.isCollapsed = !this.isCollapsed;
      this.collapsedChange.emit(this.isCollapsed);
    }
  }

  private updateSidebarClasses() {
    const sidebar = document.querySelector('.sidebar') as HTMLElement;
    if (sidebar) {
      const isMobile = this.mediaQuery.matches;
      
      if (isMobile) {
        sidebar.classList.remove('force-visible');
        
        if (this.isForcedVisible) {
          sidebar.classList.add('force-visible');
        }
      } else {
        sidebar.classList.remove('force-visible');
      }
    }
  }

  public showMobileSidebar() {
    if (this.mediaQuery.matches) {
      this.isForcedVisible = true;
      this.updateSidebarClasses();
      this.mobileMenuService.setSidebarVisible(true);
    }
  }

  public hideMobileSidebar() {
    if (this.mediaQuery.matches) {
      this.isForcedVisible = false;
      this.updateSidebarClasses();
      this.mobileMenuService.setSidebarVisible(false);
    }
  }

  public get isMobile(): boolean {
    return this.mediaQuery.matches;
  }

  public get isVisible(): boolean {
    const isMobile = this.mediaQuery.matches;
    return isMobile ? this.isForcedVisible : true;
  }

  selectMenuItem(item: MenuItem) {
    if (item.children && item.children.length > 0) {
      item.expanded = !item.expanded;
    } else {
      this.selectedItem = item.id;
      
      if (this.mediaQuery.matches) {
        this.hideMobileSidebar();
      }
      
      const route = this.buildRouteForItem(item);
      this.router.navigate(['/app', ...route.split('/')]);
    }
  }

  private buildRouteForItem(item: MenuItem): string {
    const routeMap: { [key: string]: string } = {
      'mercado-live': 'routes/mercado-live',
      'shopee': 'routes/shopee',
      'accountpayable': 'finances/accountpayable'
    };

    if (routeMap[item.id]) {
      return routeMap[item.id];
    }

    return item.id;
  }

  filterMenuItems() {
    if (!this.searchTerm) {
      this.filteredMenuItems = [...this.menuItems];
      return;
    }

    this.filteredMenuItems = this.menuItems.filter(item => {
      const itemMatches = item.label.toLowerCase().includes(this.searchTerm.toLowerCase());
      
      const childMatches = item.children?.some(child => 
        child.label.toLowerCase().includes(this.searchTerm.toLowerCase())
      );

      return itemMatches || childMatches;
    });
  }


}