import {
  AfterViewInit,
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  Component,
  ElementRef,
  HostBinding,
  Input,
  OnDestroy,
  ViewChild,
} from '@angular/core';
import { NativeContainerService } from 'native-container';
import { fromEvent, Subscription } from 'rxjs';
import { debounceTime } from 'rxjs/operators';

@Component({
  selector: 'ui-slider',
  templateUrl: 'slider.component.html',
  styleUrls: ['slider.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class UiSliderComponent implements AfterViewInit, OnDestroy {
  @HostBinding('class') clazz = 'ui-slider';

  @Input() scrollDistance = 200;

  @ViewChild('sliderWrapper', { read: ElementRef, static: true })
  slideWrapper: ElementRef;

  get slideWrapperNativeElement(): HTMLElement {
    return this.slideWrapper?.nativeElement;
  }

  get isStartVisible() {
    const { scrollLeft } = this.slideWrapperNativeElement;
    return scrollLeft === 0;
  }

  get isEndVisible() {
    const { scrollLeft, clientWidth, scrollWidth } = this.slideWrapperNativeElement;
    return scrollLeft + clientWidth === scrollWidth && scrollLeft !== 0;
  }

  @HostBinding('class.show-slide-arrows')
  get showSlideArrows() {
    const { clientWidth, scrollWidth } = this.slideWrapperNativeElement;
    return !this._nativeContainerService.isUiWebview()?.isNative && scrollWidth > clientWidth;
  }

  private subscriptions = new Subscription();

  constructor(private cdr: ChangeDetectorRef, private _nativeContainerService: NativeContainerService) {}

  ngAfterViewInit(): void {
    this.cdr.markForCheck();
    this.subscriptions.add(
      fromEvent(this.slideWrapperNativeElement, 'scroll')
        .pipe(debounceTime(100))
        .subscribe(() => this.cdr.markForCheck())
    );
  }

  ngOnDestroy() {
    this.subscriptions.unsubscribe();
  }

  scrollLeft() {
    this.slideWrapperNativeElement.scrollTo({ left: this.slideWrapperNativeElement.scrollLeft - this.scrollDistance, behavior: 'smooth' });
  }

  scrollRight() {
    this.slideWrapperNativeElement.scrollTo({ left: this.slideWrapperNativeElement.scrollLeft + this.scrollDistance, behavior: 'smooth' });
  }
}
