import { CommonModule } from '@angular/common';
import { Component, inject, input, output, viewChild } from '@angular/core';
import { RouterModule } from '@angular/router';

import { TranslateModule } from '@ngx-translate/core';
import { Store } from '@ngxs/store';
import { Observable } from 'rxjs';

import { UpdateUserProfileAction } from '../../../shared/action/account.action';
import { LogoutAction } from '../../../shared/action/auth.action';
import { Button } from '../../../shared/components/widgets/button/button';
import { ConfirmationModal } from '../../../shared/components/widgets/modal/confirmation-modal/confirmation-modal';
import { INotification } from '../../../shared/interface/notification.interface';
import { IUser } from '../../../shared/interface/user.interface';
import { TitleCasePipe } from '../../../shared/pipe/title-case.pipe';
import { AccountState } from '../../../shared/state/account.state';
import { NotificationState } from '../../../shared/state/notification.state';

@Component({
  selector: 'app-sidebar',
  imports: [CommonModule, TranslateModule, RouterModule, TitleCasePipe, Button, ConfirmationModal],
  templateUrl: './sidebar.html',
  styleUrl: './sidebar.scss',
})
export class Sidebar {
  private store = inject(Store);

  readonly show = input<boolean>();
  readonly menu = output<boolean>();

  notification$: Observable<INotification[]> = inject(Store).select(
    NotificationState.notification,
  ) as Observable<INotification[]>;
  user$: Observable<IUser> = inject(Store).select(AccountState.user) as Observable<IUser>;

  readonly ConfirmationModal = viewChild<ConfirmationModal>('confirmationModal');

  public unreadNotificationCount: number;

  constructor() {
    this.notification$.subscribe(notification => {
      this.unreadNotificationCount = notification?.filter(item => !item.read_at)?.length;
    });
  }

  logout() {
    this.store.dispatch(new LogoutAction());
  }

  openMenu(value: boolean) {
    this.menu.emit(value);
  }

  uploadImage(event: any) {
    if (event?.target?.files) {
      let form = new FormData();
      form.append('profile_image', event.target.files[0]);
      form.append('_method', 'PUT');
      this.store.dispatch(new UpdateUserProfileAction(form));
    } else {
      let form = new FormData();
      form.append('profile_image_id', '');
      form.append('_method', 'PUT');
      this.store.dispatch(new UpdateUserProfileAction(form));
    }
  }
}
