import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import {
  AbstractControl,
  FormBuilder,
  FormGroup,
  ValidatorFn,
  Validators,
} from '@angular/forms';
import { MatDialogRef } from '@angular/material/dialog';
import { fuseAnimations } from '@fuse/animations';
import { FuseAlertType } from '@fuse/components/alert';
import { BankService } from 'app/modules/polyglot/bank/services/bank.service';
import { IdentityService } from 'app/modules/polyglot/identity/services/identity.service';
import { MemberService } from 'app/modules/polyglot/member/services/member.service';
import { MemberReferrerService } from 'app/modules/polyglot/member_referrer/services/member_referrer.service';
import {
  CreateMemberRequest,
  CreateMemberResponse,
  UpdateMemberForPasswordRequest,
  UpdateMemberForPasswordResponse,
} from 'app/modules/proto/c2se/member_pb';

@Component({
  selector: 'modify-member-compose',
  templateUrl: './modify-member-compose.component.html',
  encapsulation: ViewEncapsulation.None,
  animations: fuseAnimations,
})
export class ModifyMemberComposeComponent implements OnInit {
  modifyMemberComposeForm!: FormGroup;

  isSendDisable = false;

  alert: { type: FuseAlertType; message: string } = {
    type: 'success',
    message: '수정이 성공하였습니다.',
  };

  hide: boolean = true;
  showAlert: boolean = false;

  /**
   * Constructor
   */
  constructor(
    public matDialogRef: MatDialogRef<ModifyMemberComposeComponent>,
    private _formBuilder: FormBuilder,
    private _identityService: IdentityService,
    private _memberService: MemberService,
    private _memberReferrerService: MemberReferrerService
  ) {}

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

  /**
   * On init
   */
  ngOnInit(): void {
    // Create the form
    this.modifyMemberComposeForm = this._formBuilder.group({
      username: [{ value: '', disabled: true }],
      nickname: [{ value: '', disabled: true }],
      currentPassword: ['1234', [Validators.required]],
      password: [
        '1234',
        [
          Validators.required,
          Validators.pattern('^[A-Za-z\\d@$!%*#?&]{8,20}$'),
        ],
      ],
      passwordConfirm: [
        '1234',
        [Validators.required, this.checkSameForPassword()],
      ],
    });
  }

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

  /**
   * Save and close
   */
  saveAndClose(): void {
    // Save the message as a draft
    this.saveAsDraft();

    // Close the dialog
    this.matDialogRef.close();
  }

  /**
   * Discard the message
   */
  discard(): void {}

  /**
   * Save the message as a draft
   */
  saveAsDraft(): void {}

  /**
   * Send the message
   */
  send(): void {
    if (!this.modifyMemberComposeForm?.valid) {
      return;
    }

    this.isSendDisable = true;

    const { username, nickname, currentPassword, password, passwordConfirm } =
      this.modifyMemberComposeForm?.value;

    this._memberService
      .updateMemberForPassword('', password)
      .then((res: UpdateMemberForPasswordResponse.Result) => {
        this.showAlert = true;
      })
      .catch((e) => {
        this.showAlert = true;
        this.alert = { type: 'error', message: '수정에 실패하였습니다.' };
      })
      .finally(() => setTimeout(() => this.close(), 5000));
  }

  __checkCurrentPassword(event: FocusEvent): void {
    const code = this.modifyMemberComposeForm.get('currentPassword')?.value;

    // this._memberReferrerService.getMemberReferrerByCode(code).then((result) => {
    //   if (!result.getMemberReferrer()) {
    //     this.modifyMemberComposeForm
    //       ?.get('referalCode')
    //       ?.setErrors({ notExistReferalCode: true });
    //   }
    // });
  }

  close(): void {
    this.matDialogRef.close({
      choice: true,
    });
  }

  private checkSameForPassword(): ValidatorFn {
    return (control: AbstractControl): { [key: string]: any } | null => {
      if (!control || !control.value || control.value === '') {
        return null;
      }
      const password = this.modifyMemberComposeForm?.get('password')
        ?.value as string;
      const passwordConfirm = control.value as string;

      if (password !== passwordConfirm) {
        return { passwordNotMatch: true };
      }
      return null;
    };
  }
}
