import {
  ChangeDetectionStrategy,
  Component,
  OnDestroy,
  OnInit,
  ViewChild,
} from '@angular/core';
import { MatPaginator, PageEvent } from '@angular/material/paginator';
import {
  BehaviorSubject,
  map,
  shareReplay,
  Subscription,
  switchMap,
  tap,
} from 'rxjs';

import { AnomaliesService } from '../anomalies.service';

@Component({
  selector: 'dks-anomaly-list',
  templateUrl: './anomaly-list.component.html',
  styleUrls: ['./anomaly-list.component.scss'],
  host: {
    class: 'flex flex-col h-full',
  },
  changeDetection: ChangeDetectionStrategy.OnPush,
  standalone: false,
})
export class AnomalyListComponent implements OnInit, OnDestroy {
  @ViewChild(MatPaginator, { static: true }) private paginator!: MatPaginator;

  private prevCursor = '';
  private nextCursor = '';
  private subscription = new Subscription();
  private cursor$ = new BehaviorSubject<string>(this.nextCursor);
  private paginatedAnomalies$ = this.cursor$.pipe(
    tap((cursor) => {
      if (!cursor) {
        this.prevCursor = '';
        this.nextCursor = '';
        this.paginator.firstPage();
      }
    }),
    switchMap((cursor) =>
      this.anomaliesService.getAnomaliesByPage(cursor, this.pageSize)
    ),
    tap(({ prevCursor, endCursor }) => {
      this.prevCursor = prevCursor;
      this.nextCursor = endCursor;
    }),
    shareReplay(1)
  );
  anomalies$ = this.paginatedAnomalies$.pipe(map(({ nodes }) => nodes));
  totalCount$ = this.paginatedAnomalies$.pipe(
    map(({ totalCount }) => totalCount)
  );

  pageSize = 10;

  constructor(private readonly anomaliesService: AnomaliesService) {}

  ngOnInit(): void {
    this.subscription.add(
      this.anomaliesService.anomaliesRefresh$
        .pipe(tap(() => this.cursor$.next('')))
        .subscribe()
    );
  }

  ngOnDestroy(): void {
    this.subscription.unsubscribe();
  }

  setAnomalyToSleep(anomalyId: string): void {
    this.anomaliesService.setAnomalyToSleep(anomalyId);
  }

  acceptAnomaly(anomalyId: string): void {
    this.anomaliesService.acceptAnomaly(anomalyId);
  }

  changePage({ pageIndex, previousPageIndex }: PageEvent): void {
    if (pageIndex > (previousPageIndex ?? 0)) {
      this.cursor$.next(this.nextCursor);
    } else {
      this.cursor$.next(this.prevCursor);
    }
  }
}
