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

import { User } from '../models/user';
import { UserPagination } from '../models/user-pagination';
import { UserService } from '../services/user.service';
import { Router } from '@angular/router';
import { IdentityService } from 'app/modules/polyglot/member/services/identity.service';

@Component({
  selector: 'user-list',
  templateUrl: './list.component.html',
  styles: [
    /* language=SCSS */
    `
      .user-grid {
        /*                     CB   관리  요율  상부  아이디 */
        grid-template-columns: 20px 40px 40px 100px auto;

        @screen sm {
          /*                     CB   관리  요율  상부  아이디 등급 */
          grid-template-columns: 20px 40px 40px 100px auto 40px 140px 140px;
        }

        @screen md {
          /*                     CB   관리  요율  상부  아이디  등급 예금주 보유금  게임중머니  총입출 */
          grid-template-columns: 20px 40px 40px 100px auto 40px 140px 140px;
        }

        @screen lg {
          /*                     CB   관리  요율  상부  아이디 등급  예금주  보유금 게임중머니  총입출 카지노 로그 */
          grid-template-columns: 20px 40px 40px 100px auto 40px 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;

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

  __isSearchOpened = false;
  isLoading = false;
  searchInputControl = new FormControl();
  selectedUser?: User;
  pagination?: UserPagination;

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

  /**
   * Constructor
   */
  constructor(
    private _changeDetectorRef: ChangeDetectorRef,
    private _fuseConfirmationService: FuseConfirmationService,
    private _formBuilder: FormBuilder,
    private _userService: UserService,
    private _identityService: IdentityService,
    private router: Router
  ) {}

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

  /**
   * On init
   */
  ngOnInit(): void {
    // Get the pagination
    this._userService.pagination$
      .pipe(takeUntil(this._unsubscribeAll))
      .subscribe((pagination: UserPagination | undefined) => {
        // Update the pagination
        this.pagination = pagination;

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

    // Get the products
    this.users$ = this._userService.users$;
  }

  /**
   * 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 user 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._userService.getUsers(
              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 {}

  /**
   * toggle the search
   * Used in 'bar'
   */
  __onClickSearch(): void {
    this.__isSearchOpened = !this.__isSearchOpened;
  }

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