import { Subject } from 'rxjs';

import {
  Component,
  OnInit,
  OnDestroy,
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  Inject,
  Input
} from '@angular/core';

import { Store } from '@ngrx/store';

import {
  MatDialogRef,
  MAT_DIALOG_DATA,
  MatDialog
} from '@angular/material/dialog';

import { UserInfo, GroupDetailData } from '@ucap/protocol-sync';
import { UserInfoSS, UserInfoF, UserInfoDN } from '@ucap/protocol-query';
import { UserInfo as RoomUserInfo } from '@ucap/protocol-room';
import { MatStepper } from '@angular/material/stepper';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { I18nService } from '@ucap/ng-i18n';
import { GroupActions } from '@ucap/ng-store-group';
import {
  AlertDialogComponent,
  AlertDialogData,
  AlertDialogResult
} from '@ucap/ng-ui';

export type UserInfoTypes =
  | UserInfo
  | UserInfoSS
  | UserInfoF
  | UserInfoDN
  | RoomUserInfo;

export interface CreateDialogData {
  title: string;
}
export interface CreateDialogResult {}

@Component({
  selector: 'app-dialog-group-create',
  templateUrl: './create.dialog.component.html',
  styleUrls: ['./create.dialog.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class CreateDialogComponent implements OnInit, OnDestroy {
  @Input()
  set groupName(g: string) {
    this._groupName = g;
  }
  get groupName(): string {
    return this._groupName;
  }
  _groupName: string;

  constructor(
    public dialogRef: MatDialogRef<CreateDialogData, CreateDialogResult>,
    @Inject(MAT_DIALOG_DATA) public data: CreateDialogData,
    private changeDetectorRef: ChangeDetectorRef,
    private store: Store<any>,
    private formBuilder: FormBuilder,
    private i18nService: I18nService,
    public dialog: MatDialog
  ) {}

  private ngOnDestroySubject: Subject<void>;
  currentStep = 0;
  inputForm: FormGroup;

  selectedUserList: UserInfoTypes[] = [];

  ngOnInit(): void {
    this.ngOnDestroySubject = new Subject();

    this.inputForm = this.formBuilder.group({
      groupName: [
        this.groupName,
        [
          Validators.required
          // StringUtil.includes(, CharactorType.Special),
          // this.checkBanWords(),
          // this.checkSameName()
        ]
      ]
    });
  }

  ngOnDestroy(): void {
    if (!!this.ngOnDestroySubject) {
      this.ngOnDestroySubject.complete();
    }
  }

  onClosed(event: MouseEvent): void {
    this.dialogRef.close();
  }

  onCancel(stepper: MatStepper) {
    if (stepper.selectedIndex > 0) {
      this.currentStep--;
      stepper.previous();
      return;
    }
    this.dialogRef.close();
  }
  onConfirm(stepper: MatStepper) {
    const userSeqs: string[] = [];

    this.selectedUserList.map((user) => userSeqs.push(user.seq.toString()));
    const groupName = this.inputForm.get('groupName').value as string;

    if (!groupName || groupName.localeCompare('') === 0) {
      this.dialog.open<
        AlertDialogComponent,
        AlertDialogData,
        AlertDialogResult
      >(AlertDialogComponent, {
        data: {
          title: this.i18nService.t('moreMenu.error.label'),
          html: this.i18nService.t('moreMenu.error.requireName')
        }
      });
      return;
    }

    this.store.dispatch(
      GroupActions.create({
        groupName,
        targetUserSeqs: userSeqs
      })
    );

    this.dialogRef.close();
  }
  onCompleteConfirm(stepper: MatStepper) {
    this.currentStep++;
    stepper.next();
  }

  onKeyupGroupName() {
    this.inputForm.get('groupName').markAsTouched();
  }

  onChangeUserList(data: { checked: boolean; userInfo: UserInfoSS }) {
    const i = this.selectedUserList.findIndex(
      (u) => u.seq === data.userInfo.seq
    );

    if (data.checked) {
      if (-1 === i) {
        this.selectedUserList = [...this.selectedUserList, data.userInfo];
      }
    } else {
      if (-1 < i) {
        this.selectedUserList = this.selectedUserList.filter(
          (u) => u.seq !== data.userInfo.seq
        );
      }
    }
  }

  onChangeGroupList(params: {
    isChecked: boolean;
    groupBuddyList: { group: GroupDetailData; buddyList: UserInfo[] };
  }) {
    if (params.isChecked) {
      params.groupBuddyList.buddyList.forEach((item) => {
        if (
          this.selectedUserList.filter((user) => user.seq === item.seq)
            .length === 0
        ) {
          this.selectedUserList = [...this.selectedUserList, item];
        }
      });
    } else {
      this.selectedUserList = this.selectedUserList.filter(
        (item) =>
          params.groupBuddyList.buddyList.filter((del) => del.seq === item.seq)
            .length === 0
      );
    }
  }

  onRemovedProfileSelection(userInfo: UserInfo) {
    const i = this.selectedUserList.findIndex(
      (u) => (u.seq as any) === (userInfo.seq as any)
    );

    if (-1 < i) {
      this.selectedUserList = this.selectedUserList.filter(
        (u) => (u.seq as any) !== (userInfo.seq as any)
      );
    }
  }

  removableForSelection = (userInfo: UserInfo) => {
    return true;
  };

  colorForSelection = (userInfo: UserInfo) => {
    return 'accent';
  };
}
