import {
  AfterViewInit,
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  Component,
  OnDestroy,
  OnInit,
  ViewChild,
  ViewEncapsulation,
} from '@angular/core';
import {
  FormBuilder,
  FormControl,
  FormGroup,
  Validators,
} from '@angular/forms';
import { MatTableDataSource } from '@angular/material/table';
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 { User } from '../../user/models/user';
import { CurrentUser } from '../models/current-user';
import { CurrentUserPagination } from '../models/current-user-pagination';
import { CurrentUserService } from '../services/current-user.service';
import { Router } from '@angular/router';

@Component({
  selector: 'current-user-list',
  templateUrl: './list.component.html',
  styles: [
    /* language=SCSS */
    `
      .current-user-grid {
        /*                     번호  상부 아이디  등급  위치 */
        grid-template-columns: 20px 40px auto 40px 140px;

        @screen sm {
          /*                     번호  상부 아이디  등급  위치 보유금 */
          grid-template-columns: 20px 40px auto 40px 140px 140px;
        }

        @screen md {
          /*                     번호  상부 아이디  등급  위치  보유금 게임중 사이트 */
          grid-template-columns: 20px 40px auto 40px 140px 140px 140px 140px;
        }

        @screen lg {
          /*                     번호   상부  아이디 등급  위치  보유금  게임중 사이트 카지노 배팅  로그아웃 */
          grid-template-columns: 20px 100px auto 40px 140px 140px 140px 140px 140px 140px 140px;
        }
      }
    `,
  ],
  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;

  currentUsers$!: Observable<CurrentUser[] | undefined>;
  users$!: Observable<User[] | undefined>;

  isLoading = false;
  searchInputControl = new FormControl();
  selectedCurrentUser?: CurrentUser;
  pagination?: CurrentUserPagination;
  targetForm!: FormGroup;

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

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

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

  /**
   * On init
   */
  ngOnInit(): void {
    this.targetForm = this._formBuilder.group({
      writer: [''],
      content: [''],
    });
    // Get the pagination
    this._currentUserService.pagination$
      .pipe(takeUntil(this._unsubscribeAll))
      .subscribe((pagination: CurrentUserPagination | undefined) => {
        // Update the pagination
        this.pagination = pagination;

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

    // Get the products
    this._currentUserService.currentUsers$
      .pipe(takeUntil(this._unsubscribeAll))
      .subscribe((curUsers: any[] | undefined) => {
        if (!curUsers) {
          return;
        }

        this.targetForm.patchValue(curUsers[0]);
        // Mark for check
        this._changeDetectorRef.markForCheck();
      });

    this.currentUsers$ = this._currentUserService.currentUsers$;
  }

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

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

      // If the currentUser 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._currentUserService.getCurrentUsers(
              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
  // -----------------------------------------------------------------------------------------------------

  viewUserDetail(id: string): void {
    let url: string = 'member/user/' + id;
    this.router.navigateByUrl(url);
  }
  // -----------------------------------------------------------------------------------------------------
  // @ Private methods
  // -----------------------------------------------------------------------------------------------------

  /**
   * 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;
  }
}
