import {
  ChangeDetectionStrategy,
  Component,
  ElementRef,
  EventEmitter,
  Input,
  OnChanges,
  OnInit,
  Output,
  SimpleChanges,
  ViewChild,
} from '@angular/core';

@Component({
  selector: 'ui-scroll-container',
  templateUrl: 'scroll-container.component.html',
  styleUrls: ['scroll-container.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class UiScrollContainerComponent implements OnInit {
  @ViewChild('scrollContainer', { read: ElementRef, static: false })
  scrollContainer: ElementRef;

  @Output() reachEnd = new EventEmitter<void>();

  @Output() reachStart = new EventEmitter<void>();

  @Input() containerHeight = 20; // rem

  @Input()
  direction: 'horizontal' | 'vertical' = 'vertical';

  @Input() deltaStart = 0;

  @Input() deltaEnd = 0;

  @Input() loading = false;

  @Input() itemLength: number;

  @Input() showSpacer = true;

  @Input() showScrollbar = true;

  @Input() showScrollArrow = true;

  @Input() useLoadAnimation = true;

  @Input() initialScroll: number;

  get containerHeightString() {
    return `calc(100vh - ${this.containerHeight}rem)`;
  }

  constructor() {}

  ngOnInit(): void {
    if (this.initialScroll !== undefined) {
      this.scrollTo(this.initialScroll);
    }
  }

  createSkeletons() {
    if (this.itemLength && this.itemLength !== 0) {
      return Array.from(Array(this.itemLength - 1), (_, i) => i);
    } else {
      return [];
    }
  }

  reachedEnd() {
    this.reachEnd.emit();
  }

  reachedStart() {
    this.reachStart.emit();
  }

  get scrollPersantage() {
    const scrollHeight = this.scrollContainer?.nativeElement?.scrollHeight - this.scrollContainer?.nativeElement?.clientHeight;
    if (scrollHeight === 0) {
      return 0;
    }

    const scrollTop = this.scrollContainer?.nativeElement?.scrollTop;

    return (100 / scrollHeight) * scrollTop;
  }

  get scrollPos(): number {
    return this.scrollContainer?.nativeElement?.scrollTop;
  }

  scrollTo(top: number) {
    setTimeout(() => {
      this.scrollContainer?.nativeElement?.scrollTo({ top, behavior: 'smooth' });
    }, 0);
  }

  scrollTop() {
    this.scrollTo(0);
  }
}
