/* eslint-disable @typescript-eslint/member-ordering */
import {
  Component,
  effect,
  inject,
  input,
  signal
} from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { CommonModule } from '@angular/common';
import { Actions, ofType } from '@ngrx/effects';
import { NgIcon, provideIcons } from '@ng-icons/core';
import { Store } from '@ngrx/store';
import { lucideX } from '@ng-icons/lucide';

import { Room, BanEntry } from '../../../../shared-kernel';
import { DatabaseService } from '../../../../infrastructure/persistence';
import { RoomsActions } from '../../../../store/rooms/rooms.actions';
import { UsersActions } from '../../../../store/users/users.actions';
import { APP_TRANSLATE_IMPORTS } from '../../../../core/i18n';

@Component({
  selector: 'app-bans-settings',
  standalone: true,
  imports: [
    CommonModule,
    NgIcon,
    ...APP_TRANSLATE_IMPORTS
  ],
  viewProviders: [
    provideIcons({
      lucideX
    })
  ],
  templateUrl: './bans-settings.component.html'
})
export class BansSettingsComponent {
  private store = inject(Store);
  private actions$ = inject(Actions);
  private db = inject(DatabaseService);

  /** The currently selected server, passed from the parent. */
  server = input<Room | null>(null);
  /** Whether the current user is admin of this server. */
  isAdmin = input(false);

  bannedUsers = signal<BanEntry[]>([]);

  constructor() {
    effect(() => {
      const roomId = this.server()?.id;

      if (!roomId) {
        this.bannedUsers.set([]);
        return;
      }

      void this.loadBansForServer(roomId);
    });

    this.actions$
      .pipe(
        ofType(
          UsersActions.banUserSuccess,
          UsersActions.unbanUserSuccess,
          UsersActions.loadBansSuccess,
          RoomsActions.updateRoom
        ),
        takeUntilDestroyed()
      )
      .subscribe(() => {
        const roomId = this.server()?.id;

        if (roomId) {
          void this.loadBansForServer(roomId);
        }
      });
  }

  unbanUser(ban: BanEntry): void {
    this.store.dispatch(UsersActions.unbanUser({ roomId: ban.roomId,
      oderId: ban.oderId }));
  }

  private async loadBansForServer(roomId: string): Promise<void> {
    this.bannedUsers.set(await this.db.getBansForRoom(roomId));
  }

  formatExpiry(timestamp: number): string {
    const date = new Date(timestamp);

    return (
      date.toLocaleDateString() +
      ' ' +
      date.toLocaleTimeString([], { hour: '2-digit',
        minute: '2-digit' })
    );
  }
}
