import { CommonModule } from '@angular/common';
import {
  AfterContentChecked,
  AfterContentInit,
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  Component,
  ContentChildren,
  ElementRef,
  Input,
  QueryList,
  ViewChild
} from '@angular/core';
import { Utils } from '../../utils/utils.util';
import { BreadcrumbItemComponent } from '../breadcrumb-item/breadcrumb-item.component';

@Component({
  selector: 'nj-breadcrumb',
  templateUrl: './breadcrumb.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush,
  standalone: true,
  imports: [BreadcrumbItemComponent, CommonModule]
})
export class BreadcrumbComponent implements AfterContentInit, AfterContentChecked {
  /**
   * Describes the navigation to screen reader users (who navigate the page using landmarks)
   *
   * @default "Breadcrumbs"
   */
  @Input() ariaLabel: string = 'Breadcrumbs';

  /**
   * Accessible text alternative for the "show more" button when the breadcrumb is minified.
   *
   * @default "Show hidden items"
   */
  @Input() showMoreLabel: string = 'Show hidden items';

  /**
   * @ignore
   */
  isMinified: boolean;

  /**
   * @ignore
   */
  leftContent: BreadcrumbItemComponent[];

  /**
   * @ignore
   */
  rightContent: BreadcrumbItemComponent;

  constructor(private cdr: ChangeDetectorRef) {}

  /**
   * @ignore
   */
  @ContentChildren(BreadcrumbItemComponent)
  breadcrumbItems: QueryList<BreadcrumbItemComponent>;

  /**
   * @ignore
   */
  @ViewChild('olRef') olRef: ElementRef<HTMLOListElement>;

  ngAfterContentInit() {
    this.isMinified = this.breadcrumbItems?.toArray()?.length > 4;
    this.leftContent = this.getLeftContentToDisplay();
    this.rightContent = this.getRightContentToDisplay();
  }

  ngAfterContentChecked() {
    this.cdr.markForCheck();
  }

  /**
   * @ignore
   */
  seeAll() {
    this.isMinified = false;
    this.leftContent = this.getLeftContentToDisplay();
    this.rightContent = this.getRightContentToDisplay();
    this.cdr.markForCheck();

    // Focus first revealed item
    setTimeout(() => {
      (this.olRef.nativeElement.childNodes[2] as HTMLLIElement)?.querySelector('a')?.focus();
    });
  }

  /**
   * @ignore
   */
  getLeftContentToDisplay(): BreadcrumbItemComponent[] {
    const breadcrumbItemsArray = this.breadcrumbItems?.toArray();
    if (Utils.isUndefinedOrNull(breadcrumbItemsArray)) {
      return;
    }
    return this.isMinified ? breadcrumbItemsArray.splice(0, 1) : breadcrumbItemsArray;
  }

  /**
   * @ignore
   */
  getRightContentToDisplay(): BreadcrumbItemComponent {
    if (!this.isMinified) {
      return;
    }
    const breadcrumbItemsArray = this.breadcrumbItems?.toArray();
    const breadcrumbItemsLength = breadcrumbItemsArray?.length;
    return breadcrumbItemsArray[breadcrumbItemsLength - 1];
  }
}
