import {
  Component,
  OnInit,
  OnDestroy,
  AfterViewInit,
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  Inject,
  ViewChild,
  ComponentFactoryResolver,
  ViewContainerRef,
  ComponentRef
} from '@angular/core';
import { UserInfo, GroupDetailData } from '@ucap/protocol-sync';
import {
  UserInfoSS,
  UserInfoF,
  UserInfoDN,
  DeptInfo
} from '@ucap/protocol-query';

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

import { Subject, combineLatest } from 'rxjs';
import { AppAuthenticationService } from '@app/services/app-authentication.service';
import { SelectUserDialogType } from '@app/types';
import { RoomInfo, UserInfo as RoomUserInfo } from '@ucap/protocol-room';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { SelectUserSectionComponent } from '../../select-user.section.component';
import { GroupActions } from '@ucap/ng-store-group';
import { UserInfoTypes } from '../profile-list-item.component';

import { GroupInputComponent } from '../group-input.component';

export interface CreateChatDialogData {
  type?: SelectUserDialogType;
  title: string;
  /** CASE :: EditMember */
  group?: GroupDetailData;
  /** CASE :: EventForward */
  ignoreRoom?: RoomInfo[];
  /** CASE :: EditChatMember */
  curRoomUser?: (
    | UserInfo
    | UserInfoSS
    | UserInfoF
    | UserInfoDN
    | RoomUserInfo
  )[];
}
export interface CreateChatDialogResult {
  choice: boolean;
  groupName?: string;
  oldGroup?: GroupDetailData;
  selectedUserList?: (
    | UserInfo
    | UserInfoSS
    | UserInfoF
    | UserInfoDN
    | RoomUserInfo
  )[];
  selectedRoom: RoomInfo;
}

@Component({
  selector: 'app-create-chat.dialog',
  templateUrl: './create-chat.dialog.component.html',
  styleUrls: ['./create-chat.dialog.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class CreateChatDialogComponent implements OnInit, OnDestroy {
  @ViewChild('selectBoxUserComponent', { static: false })
  selectBoxUserComponent: SelectUserSectionComponent;
  @ViewChild('dialogContainer', { static: true, read: ViewContainerRef })
  dialogContainer: ViewContainerRef;

  componentRef: ComponentRef<any>;

  constructor(
    public dialogRef: MatDialogRef<
      CreateChatDialogData,
      CreateChatDialogResult
    >,
    @Inject(MAT_DIALOG_DATA) public data: CreateChatDialogData,
    private changeDetectorRef: ChangeDetectorRef,
    private store: Store<any>,
    private appAuthenticationService: AppAuthenticationService,
    private cfResolver: ComponentFactoryResolver
  ) {}

  private ngOnDestroySubject = new Subject<boolean>();

  selectedUserList: UserInfoTypes[] = [];
  SelectUserDialogType = SelectUserDialogType;
  selectedRoom: RoomInfo;

  groupName: string;

  ngOnInit(): void {
    this.loadComponent();
  }

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

  loadComponent() {
    switch (this.data.type) {
      case SelectUserDialogType.NewGroup:
      case SelectUserDialogType.ModifyGroup:
        {
          this.dialogContainer.clear();
          const factory = this.cfResolver.resolveComponentFactory(
            GroupInputComponent
          );

          this.componentRef = this.dialogContainer.createComponent(factory);
          const cpInstance = this.componentRef.instance;
          cpInstance.dialogType = this.data.type;

          cpInstance.groupName =
            !!this.data.group && !!this.data.group.name
              ? this.data.group.name
              : '';
          cpInstance.inputPlacholder = '그룹';
          cpInstance.cancel.subscribe(() => {
            this.dialogRef.close();
          });
          cpInstance.confirm.subscribe(() => {
            this.groupName = this.componentRef.instance.getGroupName();
            this.doAction();
          });
          cpInstance.completeConfirm.subscribe(() => {
            this.groupName = this.componentRef.instance.getGroupName();
            this.showSelectUserComponent();
          });
        }
        break;
      case SelectUserDialogType.NewChat:
        {
          // 새로운 대화 유형 & 대화방 이름 섹션 컴포넌트
          // 유저 선택 컴포넌트
        }
        break;
      case SelectUserDialogType.EditChatMember:
        {
          // 유저 선택 컴포넌트
        }
        break;
      case SelectUserDialogType.EditMember:
        {
          // 그룹 멤버 관리 컴포넌트
          // 유저 선택 컴포넌트
        }
        break;
      case SelectUserDialogType.MessageForward:
        {
          // 유저 선택 컴포넌트
        }
        break;
    }
  }
  onClickChoice(choice: boolean) {
    if (!choice) {
      this.dialogRef.close();
      return;
    }
  }
  getBtnValid() {}
  getChipsRemoveYn(userInfo: UserInfo) {}
  onClickDeleteUser(userInfo: UserInfo) {}

  onChangeSelectedUserList(userList: UserInfoTypes[]) {
    this.selectedUserList = userList;
    this.changeDetectorRef.markForCheck();
  }

  doAction() {
    this.dialogRef.close({
      choice: true,
      selectedUserList: this.selectedUserList,
      selectedRoom: this.selectedRoom,
      groupName: this.groupName,
      oldGroup: undefined
    });
  }

  private showSelectUserComponent() {
    this.dialogContainer.clear();
    const factory = this.cfResolver.resolveComponentFactory(
      SelectUserSectionComponent
    );

    this.componentRef = this.dialogContainer.createComponent(factory);
    this.componentRef.instance.cancel.subscribe(() => {
      if (
        this.data.type === SelectUserDialogType.NewGroup ||
        this.data.type === SelectUserDialogType.ModifyGroup
      ) {
        this.loadComponent();
      }
    });
    this.componentRef.instance.confirm.subscribe(() => {
      this.doAction();
    });

    this.componentRef.instance.changeUserList.subscribe((list) => {
      this.selectedUserList = list;
    });
  }
}