import {
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  Component,
  EventEmitter,
  Input,
  OnDestroy,
  OnInit,
  Output,
} from '@angular/core';
import { BehaviorSubject } from 'rxjs';
import { skip } from 'rxjs/operators';
import { UiIconType } from '@ui/icon/icon-type.enum';
import { UiIconSize } from '@ui/icon/icon-size.enum';
import { uuid } from '@utils/uuid.util';

@Component({
  selector: 'ui-expansion-panel',
  templateUrl: './expansion-panel.component.html',
  styleUrls: ['./expansion-panel.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ExpansionPanelComponent implements OnInit, OnDestroy {
  @Input() uiContentId: string = 'ui-expansion-panel--container__' + uuid();
  @Input() uiTriggerId: string = 'ui-expansion-panel--toggle-button__' + uuid();
  @Input() uiSecondary = false;
  @Output() uiExpand = new EventEmitter<void>();
  @Output() uiCollapse = new EventEmitter<void>();
  @Output() uiClick = new EventEmitter<MouseEvent>();

  isExpanded$: BehaviorSubject<boolean> = new BehaviorSubject(false);
  UiIconType = UiIconType;
  UiIconSize = UiIconSize;

  constructor(private changeDetectorRef: ChangeDetectorRef) {}

  @Input()
  set uiExpanded(expanded: boolean) {
    this.isExpanded$.next(expanded);
  }

  ngOnInit(): void {
    this.isExpanded$.pipe(skip(1)).subscribe(val => {
      this.changeDetectorRef.markForCheck();
      this.togglePanelEventHandler(val);
    });
  }

  ngOnDestroy(): void {
    this.isExpanded$.unsubscribe();
  }

  get cssModifiers(): { [cssClass: string]: boolean } {
    return {
      'ui-expansion-panel--collapsed': !this.isExpanded$.value,
      'ui-expansion-panel--secondary': this.uiSecondary,
    };
  }

  get cssModifiersIcon(): { [cssClass: string]: boolean } {
    return { 'ui-expansion-panel__icon--expanded': this.isExpanded$.value };
  }

  clickTriggerHandler(mouseEvent: MouseEvent): void {
    this.uiClick.emit(mouseEvent);
    this.isExpanded$.next(!this.isExpanded$.value);
  }

  togglePanelEventHandler(isExpanded: boolean): void {
    if (isExpanded) {
      this.uiExpand.emit();
    } else {
      this.uiCollapse.emit();
    }
  }
}
