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,
  of,
  Subject,
  switchMap,
  takeUntil,
} from 'rxjs';
import { fuseAnimations } from '@fuse/animations';
import { FuseConfirmationService } from '@fuse/services/confirmation';

import { Withdraw } from '../models/withdraw';
import { WithdrawPagination } from '../models/withdraw-pagination';
import { WithdrawService } from '../services/withdraw.service';
import { ActivatedRoute, Router } from '@angular/router';
import { ListMemberBankWithdrawsResponse } from 'app/modules/proto/c2se/member_bank_withdraw_pb';
import { MemberBankWithdraw } from 'app/modules/proto/models/member_bank_withdraw_pb';

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

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

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

        @screen lg {
          grid-template-columns: 40px 140px auto 80px 140px 40px 120px 120px 120px 40px 40px;
        }
      }

      .mat-tooltip {
        white-space: pre-line;
      }
    `,
  ],
  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;

  bankWithdraw$!: Observable<MemberBankWithdraw[] | undefined>;

  __isSearchOpened = false;
  isLoading = false;
  searchInputControl = new FormControl();
  selectedWithdraw?: Withdraw;
  pagination?: WithdrawPagination;

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

  /**
   * Constructor
   */
  constructor(
    private _activatedRoute: ActivatedRoute,
    private _changeDetectorRef: ChangeDetectorRef,
    private _fuseConfirmationService: FuseConfirmationService,
    private _formBuilder: FormBuilder,
    private _withdrawService: WithdrawService,
    private router: Router
  ) {}

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

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

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

    // Get the products

    this._activatedRoute.data.subscribe((data) => {
      let listBankWithdrawResult: ListMemberBankWithdrawsResponse.Result =
        data['bankWithdraw'];
      this.bankWithdraw$ = of(
        listBankWithdrawResult.getMemberBankWithdrawsList()
      );

      console.log(
        'bankWithdraw: ',
        listBankWithdrawResult.getMemberBankWithdrawsList()
      );

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

  /**
   * 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 withdraw 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._withdrawService.getWithdraws(
              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;
  }

  __getMemoTooltop(withdraw: MemberBankWithdraw): string {
    if (!withdraw.getMemo() || withdraw.getMemo() === '') {
      return '메모없음';
    }

    const resultMemoTooltip = withdraw.getMemo();
    return resultMemoTooltip;
  }
}
