import { animate, style, transition, trigger } from '@angular/animations';
import { Overlay, OverlayPositionBuilder, OverlayRef } from '@angular/cdk/overlay';
import { TemplatePortal } from '@angular/cdk/portal';
import {
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  Component,
  EmbeddedViewRef,
  OnDestroy,
  OnInit,
  TemplateRef,
  ViewChild,
  ViewContainerRef,
} from '@angular/core';
import { Subject } from 'rxjs';

@Component({
  selector: 'shell-filter-overlay',
  templateUrl: 'filter-overlay.component.html',
  styleUrls: ['filter-overlay.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  exportAs: 'shellFilterOverlay',
  animations: [
    trigger('slideInOut', [
      transition(':enter', [style({ transform: 'translateX(100%)' }), animate('250ms', style({ transform: 'translateX(0%)' }))]),
      transition(':leave', [style({ transform: '*' }), animate('250ms', style({ transform: 'translateX(100%)' }))]),
    ]),
  ],
})
export class ShellFilterOverlayComponent implements OnInit, OnDestroy {
  @ViewChild('filterOverlay')
  filterOverlay: TemplateRef<any>;

  private viewRef: EmbeddedViewRef<any>;
  private overlayRef: OverlayRef;
  private _onDestroy$ = new Subject<void>();

  get isOpen() {
    return !!this.viewRef;
  }

  constructor(
    private _viewContainerRef: ViewContainerRef,
    private _overlay: Overlay,
    private _cdr: ChangeDetectorRef,
    private _overlayPositionBuilder: OverlayPositionBuilder
  ) {}

  ngOnInit(): void {
    this.createOverlay();
  }

  ngOnDestroy(): void {
    this.overlayRef?.dispose();
    this._onDestroy$.next();
    this._onDestroy$.complete();
  }

  createOverlay() {
    this.overlayRef = this._overlay.create({
      positionStrategy: this._overlayPositionBuilder.global().bottom('0px').right('0px').left('0px').top('8.375rem'),
      hasBackdrop: true,
      backdropClass: 'cdk-overlay-transparent-backdrop',
    });
  }

  open() {
    const dropdownPortal = new TemplatePortal(this.filterOverlay, this._viewContainerRef);

    if (!!this.viewRef) {
      this.close();
    }

    this.viewRef = this.overlayRef.attach(dropdownPortal);
    this._cdr.markForCheck();
  }

  close() {
    this.viewRef?.destroy();
    this.overlayRef.detach();
    delete this.viewRef;
    this._cdr.markForCheck();
  }
}
