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 { User } from '../models/user';
import { UserService } from '../services/user.service';
import { ActivatedRoute } from '@angular/router';
import { GetMemberResponse } from 'app/modules/proto/c2se/member_pb';
import { MemberModel } from 'app/modules/proto/models/member_pb';
import { MemberService } from 'app/modules/polyglot/member/services/member.service';
import { MemberLevelService } from 'app/modules/polyglot/member_level/services/member_level.service';
import { BankService } from 'app/modules/polyglot/bank/services/bank.service';
import { MemberLevel } from 'app/modules/proto/models/member_level_pb';
import { Bank } from 'app/modules/proto/models/bank_pb';
import { SiteService } from 'app/modules/polyglot/site/services/site.service';
import { Site } from 'app/modules/proto/models/site_pb';

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

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

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

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

  isLoading = false;
  searchInputControl = new FormControl();
  memberViewForm!: FormGroup;
  /* selectedUser?: User; */
  selectedUser?: MemberModel;

  memberLevels!: MemberLevel[];
  banks!: Bank[];
  sites!: Site[];

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

  /**
   * Constructor
   */
  constructor(
    private _activatedRoute: ActivatedRoute,
    private _changeDetectorRef: ChangeDetectorRef,
    private _fuseConfirmationService: FuseConfirmationService,
    private _formBuilder: FormBuilder,
    private _userService: UserService,
    private _memberService: MemberService,
    private _memberLevelService: MemberLevelService,
    private _bankService: BankService,
    private _siteService: SiteService
  ) {}

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

  /**
   * On init
   */
  ngOnInit(): void {
    this.memberViewForm = this._formBuilder.group({
      id: [''],
      username: [{ value: '', disabled: true }],
      signinPw: [{ value: '' }],
      exchangePw: [''],
      description: [''],
      tags: [[]],
      nickname: [{ value: '', disabled: true }],
      ownCash: [''],
      mobilePhoneNumber: [''],
      level: [''],
      state: [''],
      isExcahngeMoney: [''],
      bankId: [''],
      accountNumber: [''],
      accountHolder: [''],
      comp: [''],
      coupon: [''],
      recommender: [{ value: '', disabled: true }],
      changeSite: [''],
      recommendCount: [''],
      hodingGameMoney: [{ value: '0', disabled: true }],
      memo: [''],
      bacaraRate: [],
      rulletRate: [],
      dragonRate: [],
      etcRate: [],
      slotRate: [],
      casinoRusingRate: [],
      slotRusingRate: [],
    });

    // Get the User
    /* this._userService.user$
      .pipe(takeUntil(this._unsubscribeAll))
      .subscribe((user: User | undefined) => {
        if (!user) {
          return;
        }
        this.selectedUser = user;

        this.memberViewForm.patchValue(user);
        // Mark for check
        this._changeDetectorRef.markForCheck();
      }); */

    /* this.user$ = this._userService.user$; */

    this._siteService
      .listSites()
      .then((result) => (this.sites = result.getSitesList()));
    this._memberLevelService.listMemberLevels().then((result) => {
      this.memberLevels = result
        .getMemberLevelsList()
        .filter((v) => !!v.getShow());
    });
    this._bankService
      .listBanks()
      .then((result) => (this.banks = result.getBanksList()));

    this._activatedRoute.data.subscribe((data) => {
      let member: GetMemberResponse.Result = data['member'];

      this.selectedUser = member.getMember();

      /* console.log('dddd', listMemberResult.getMembersList()); */
      this.memberViewForm.patchValue({
        username: this.selectedUser?.getUsername(),
        signinPw: '',
        exchangePw: '',
        mobilePhoneNumber: this.selectedUser?.getMobilePhoneNumber(),
        levelId: this.selectedUser?.getMemberLevel()?.getId(),
        state: this.selectedUser?.getState(),
        nickname: this.selectedUser?.getNickname(),
        bankId: this.selectedUser?.getBankAccount()?.getId(),
      });
      // Mark for check
      this._changeDetectorRef.markForCheck();
    });
  }

  /**
   * After view init
   */
  ngAfterViewInit(): void {}

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

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

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

  __modifyMember(): void {
    const valueForm = this.memberViewForm.value;
    console.log('v: ', valueForm);
    /* this._memberService.updateMember(
      this.selectedUser!.getId(),
      this.selectedUser!.getSite()!.getId(),
      this.selectedUser!.getMemberLevel()!.getId(),
      'beteran',
      valueForm.mobilePhoneNumber
    ); */
  }
}
