import { Component, Input, Output, EventEmitter, ChangeDetectionStrategy, OnInit, OnChanges, SimpleChanges, ChangeDetectorRef } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MenuItemComponent, MenuItemData } from './menu-item.component';
import { MenuContainerComponent } from './menu-container.component';

@Component({
  selector: 'ui-menu-submenu',
  standalone: true,
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [CommonModule, MenuItemComponent, MenuContainerComponent],
  template: `
    <div class="submenu-wrapper" [class.submenu-wrapper--open]="isOpen">
      <!-- Parent menu item -->
      <ui-menu-item 
        [data]="parentItem"
        [size]="size"
        [variant]="variant"
        [iconPosition]="iconPosition"
        [showDivider]="showDivider"
        [indent]="indent"
        [dense]="dense"
        (submenuToggle)="toggleSubmenu($event)"
        (itemClick)="onParentClick($event)"
      />
      
      <!-- Submenu content -->
      @if (isOpen) {
        <div class="submenu-content">
          <ui-menu-container 
            [elevation]="submenuElevation"
            [spacing]="submenuSpacing"
            [rounded]="false"
            [dense]="dense"
            class="menu-submenu"
          >
            <ng-content></ng-content>
          </ui-menu-container>
        </div>
      }
    </div>
  `,
  styleUrls: ['./menu-submenu.component.scss'],
  animations: []
})
export class MenuSubmenuComponent implements OnInit, OnChanges {
  @Input() parentItem!: MenuItemData;
  @Input() size: 'sm' | 'md' | 'lg' = 'md';
  @Input() variant: 'default' | 'primary' | 'secondary' | 'danger' = 'default';
  @Input() iconPosition: 'left' | 'right' = 'left';
  @Input() showDivider = false;
  @Input() indent = false;
  @Input() dense = false;
  @Input() isOpen = false;
  @Input() submenuElevation: 'none' | 'sm' | 'md' | 'lg' = 'none';
  @Input() submenuSpacing: 'none' | 'xs' | 'sm' | 'md' | 'lg' = 'xs';

  @Output() submenuToggled = new EventEmitter<{ item: MenuItemData; isOpen: boolean }>();
  @Output() parentItemClick = new EventEmitter<MenuItemData>();

  constructor(private cdr: ChangeDetectorRef) {}

  ngOnInit(): void {
    // Initialize parent item active state based on submenu open state
    this.updateParentItemState();
  }

  ngOnChanges(changes: SimpleChanges): void {
    // Update parent item state when isOpen input changes
    if (changes['isOpen']) {
      this.updateParentItemState();
    }
  }

  toggleSubmenu(item: MenuItemData): void {
    this.isOpen = !this.isOpen;
    this.updateParentItemState();
    this.submenuToggled.emit({ item, isOpen: this.isOpen });
  }

  private updateParentItemState(): void {
    // Create a new object reference to trigger change detection
    this.parentItem = {
      ...this.parentItem,
      active: this.isOpen
    };
  }

  onParentClick(item: MenuItemData): void {
    this.parentItemClick.emit(item);
  }
}