import {
  AfterViewInit,
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  Component,
  OnDestroy,
  OnInit,
  ViewChild,
  ViewEncapsulation,
} from '@angular/core';
import {
  FormBuilder,
  FormControl,
  FormGroup,
  Validators,
} from '@angular/forms';
import { MatCheckboxChange } from '@angular/material/checkbox';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import {
  debounceTime,
  map,
  merge,
  Observable,
  Subject,
  switchMap,
  takeUntil,
} from 'rxjs';
import { fuseAnimations } from '@fuse/animations';
import { FuseConfirmationService } from '@fuse/services/confirmation';

import { Popup } from '../models/popup';
import { PopupPagination } from '../models/popup-pagination';
import { PopupService } from '../services/popup.service';
import { Router } from '@angular/router';
import { MatTableDataSource } from '@angular/material/table';

@Component({
  selector: 'popup-list',
  templateUrl: './list.component.html',
  styles: [
    /* language=SCSS */
    `
      .popup-grid {
        grid-template-columns: 60px auto 40px;

        @screen sm {
          grid-template-columns: 60px 60px 60px 60px 60px 60px auto 60px;
        }

        @screen md {
          grid-template-columns: 60px 60px 60px 60px 60px 60px auto 60px 60px;
        }

        @screen lg {
          grid-template-columns: 60px 70px 70px 70px 70px 100px 60px 60px auto 60px 60px 60px 60px;
        }
      }
    `,
  ],
  encapsulation: ViewEncapsulation.None,
  changeDetection: ChangeDetectionStrategy.OnPush,
  animations: fuseAnimations,
})
export class ListComponent implements OnInit, AfterViewInit, OnDestroy {
  @ViewChild(MatPaginator) private _paginator!: MatPaginator;
  @ViewChild(MatSort) private _sort!: MatSort;

  popups$!: Observable<Popup[] | undefined>;

  isLoading = false;
  searchInputControl = new FormControl();
  selectedPopup?: Popup;
  pagination?: PopupPagination;

  private _unsubscribeAll: Subject<any> = new Subject<any>();

  popupTableColumns: string[] = [
    'index',
    'title',
    'widthSize',
    'heightSize',
    'topMargin',
    'leftMargin',
    'site',
    'useOrNot',
    'btn',
  ];

  popupDataSource: MatTableDataSource<Popup> = new MatTableDataSource();

  /**
   * Constructor
   */
  constructor(
    private _changeDetectorRef: ChangeDetectorRef,
    private _fuseConfirmationService: FuseConfirmationService,
    private _formBuilder: FormBuilder,
    private _popupService: PopupService,
    private router: Router
  ) {}

  // -----------------------------------------------------------------------------------------------------
  // @ Lifecycle hooks
  // -----------------------------------------------------------------------------------------------------

  /**
   * On init
   */
  ngOnInit(): void {
    this._popupService.popups$
      .pipe(takeUntil(this._unsubscribeAll))
      .subscribe((popups: Popup[] | undefined) => {
        if (!popups) {
          return;
        }

        this.popupDataSource.data = popups;
        // Mark for check
        this._changeDetectorRef.markForCheck();
      });
  }

  /**
   * After view init
   */
  ngAfterViewInit(): void {
    if (this._sort && this._paginator) {
      // Set the initial sort
      this._sort.sort({
        id: 'name',
        start: 'asc',
        disableClear: true,
      });

      // Mark for check
      this._changeDetectorRef.markForCheck();

      // If the popup changes the sort order...
      this._sort.sortChange
        .pipe(takeUntil(this._unsubscribeAll))
        .subscribe(() => {
          // Reset back to the first page
          this._paginator.pageIndex = 0;
        });

      // Get products if sort or page changes
      merge(this._sort.sortChange, this._paginator.page)
        .pipe(
          switchMap(() => {
            this.isLoading = true;
            return this._popupService.getPopups(
              this._paginator.pageIndex,
              this._paginator.pageSize,
              this._sort.active,
              this._sort.direction
            );
          }),
          map(() => {
            this.isLoading = false;
          })
        )
        .subscribe();
    }
  }

  /**
   * On destroy
   */
  ngOnDestroy(): void {
    // Unsubscribe from all subscriptions
    this._unsubscribeAll.next(null);
    this._unsubscribeAll.complete();
  }

  // -----------------------------------------------------------------------------------------------------
  // @ Public methods
  // -----------------------------------------------------------------------------------------------------

  // -----------------------------------------------------------------------------------------------------
  // @ Private methods
  // -----------------------------------------------------------------------------------------------------

  __viewPopupDetail(id: string): void {
    let url: string = 'board/popup/view/' + id;
    this.router.navigateByUrl(url);
  }

  __createPopup(): void {
    let url: string = 'board/popup/redit/';
    this.router.navigateByUrl(url);
  }

  __modifyPopup(id: string): void {
    let url: string = 'board/popup/redit/' + id;
    this.router.navigateByUrl(url);
  }
  /**
   * Create product
   */
  __createProduct(): void {}

  /**
   * Toggle product details
   *
   * @param productId
   */
  __toggleDetails(productId: string): void {}

  /**
   * Track by function for ngFor loops
   *
   * @param index
   * @param item
   */
  __trackByFn(index: number, item: any): any {
    return item.id || index;
  }
}
