import { ChangeDetectionStrategy, Component, OnInit, ViewEncapsulation } from '@angular/core';
import { ComponentStore } from '@ngrx/component-store';
import { Group, groupBy } from '@ui/common';
import { UiModalRef } from '@ui/modal';
import { EnvelopeDTO, MessageBoardItemDTO } from 'apps/hub/notifications/src/lib/defs';
import { combineLatest } from 'rxjs';
import { map } from 'rxjs/operators';

interface ModalNotificationComponentState {
  activeCard: string;
  groupedNotifications: Group<string, MessageBoardItemDTO>[];
}

@Component({
  selector: 'modal-notifications',
  templateUrl: 'notifications.component.html',
  styleUrls: ['notifications.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  encapsulation: ViewEncapsulation.None,
})
export class ModalNotificationsComponent extends ComponentStore<ModalNotificationComponentState> implements OnInit {
  set activeCard(activeCard: string) {
    if (this.activeCard !== activeCard) {
      this.patchState({ activeCard });
    }
  }

  activeCard$ = this.select((s) => s.activeCard);

  get activeCard() {
    return this.get((s) => s.activeCard);
  }

  get groupedNotifications() {
    return this.get((s) => s.groupedNotifications);
  }
  groupedNotifications$ = this.select((s) => s.groupedNotifications);

  set groupedNotifications(groupedNotifications: Group<string, MessageBoardItemDTO>[]) {
    this.patchState({ groupedNotifications });
  }

  activeNotifications$ = combineLatest([this.activeCard$, this.groupedNotifications$]).pipe(
    map(([activeCard, notifications]) => notifications.find((n) => n.group === activeCard)?.items)
  );

  constructor(private _modalRef: UiModalRef<any, EnvelopeDTO<MessageBoardItemDTO[]>>) {
    super({
      activeCard: undefined,
      groupedNotifications: groupBy(_modalRef.data.data, (item: MessageBoardItemDTO) => item.category),
    });
  }

  ngOnInit() {
    this.patchState({ activeCard: this.groupedNotifications?.find((_) => true)?.group });
  }

  close() {
    this._modalRef.close();
  }
}
