import {
  AfterViewChecked,
  ChangeDetectorRef,
  Component,
  ElementRef,
  Input,
  OnDestroy,
  OnInit,
  ViewChild
} from '@angular/core';
import { IObjectListController } from '../interfaces/object-list-controller';
import { Subscription } from 'rxjs';
import { ICardViewData } from '../interfaces/card-data/card-view-data';
import { ThemingService } from '@shared/ui/theming/theming.service';

@Component({
  selector: 'app-card-view',
  templateUrl: './card-view.component.html',
  styleUrls: ['./card-view.component.scss']
})
export class CardViewComponent implements OnInit, OnDestroy, AfterViewChecked {
  @Input() objectsListController: IObjectListController;
  cardViewDataSubscription: Subscription = null;
  cardViewData: ICardViewData;
  noItemsTxt = $localize`No items`;
  @ViewChild('cardViewContainer') cardViewContainer: ElementRef;
  dummyCards = [];
  cardViewContainerWidth;
  private appTopOffsetSubscription: Subscription;
  noObjectsBaseTopOffset = 200;
  noObjectsTopOffset = '200px';

  constructor(
    private themingService: ThemingService,
    private cdr: ChangeDetectorRef,
  ) {
  }

  ngOnInit() {
    if (this.objectsListController) {
      this.objectsListController.cardViewData$.subscribe(response => {
        this.cardViewData = response;
        if (this.cardViewContainer) {
          this.cardViewContainerChanged();
          this.cdr.detectChanges();
        }
      });
    } else {
      console.error('Card data cannot be received due to missing objectsListController');
    }

    this.appTopOffsetSubscription = this.themingService.observableAppTopOffset.subscribe(value => {
      const newOffset = this.noObjectsBaseTopOffset + value;
      this.noObjectsTopOffset = `${newOffset}px`;
    });
  }

  ngAfterViewChecked() {
    if (this.cardViewContainerWidth !== this.cardViewContainer.nativeElement.offsetWidth) {
      this.cardViewContainerChanged();
      this.cdr.detectChanges();
    }
  }

  cardViewContainerChanged() {
    this.cardViewContainerWidth = this.cardViewContainer.nativeElement.offsetWidth;
    if (this.cardViewData?.cards) {
      const cardsPerRow = Math.floor(this.cardViewContainerWidth / 345);
      if (cardsPerRow > 1) {
        const cardsOnLastRow = this.cardViewData?.cards.length % cardsPerRow;
        if (cardsOnLastRow === 0) {
          this.dummyCards = [];
        } else {
          this.dummyCards = Array(cardsPerRow - (this.cardViewData?.cards.length % cardsPerRow)).fill(1);
        }
      } else {
        this.dummyCards = [];
      }
    }
  }

  ngOnDestroy(): void {
    if (this.cardViewDataSubscription) {
      this.cardViewDataSubscription.unsubscribe();
      this.cardViewDataSubscription = null;
    }
    if (this.appTopOffsetSubscription) {
      this.appTopOffsetSubscription.unsubscribe();
      this.appTopOffsetSubscription = null;
    }
  }

}
