import {
  Component,
  HostListener,
  computed,
  effect,
  inject,
  input,
  output,
  signal
} from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { ModalBackdropComponent } from '../modal-backdrop/modal-backdrop.component';
import { APP_TRANSLATE_IMPORTS } from '../../../core/i18n';
import {
  Room,
  RoomMember,
  User
} from '../../../shared-kernel';
import { AppI18nService } from '../../../core/i18n';

export interface LeaveServerDialogResult {
  nextOwnerKey?: string;
}

@Component({
  selector: 'app-leave-server-dialog',
  standalone: true,
  imports: [
    CommonModule,
    FormsModule,
    ModalBackdropComponent,
    ...APP_TRANSLATE_IMPORTS
  ],
  templateUrl: './leave-server-dialog.component.html'
})
export class LeaveServerDialogComponent {
  private readonly appI18n = inject(AppI18nService);

  room = input.required<Room>();
  currentUser = input<User | null>(null);
  confirmed = output<LeaveServerDialogResult>();
  cancelled = output<undefined>();

  selectedOwnerKey = signal('');

  isOwner = computed(() => {
    const room = this.room();
    const user = this.currentUser();

    if (!room || !user)
      return false;

    return room.hostId === user.id || room.hostId === user.oderId;
  });

  ownerCandidates = computed(() => {
    const room = this.room();
    const user = this.currentUser();
    const userIds = new Set([user?.id, user?.oderId].filter((value): value is string => !!value));

    return (room.members ?? []).filter((member) => !userIds.has(member.id) && !userIds.has(member.oderId || ''));
  });

  constructor() {
    effect(() => {
      this.room();
      this.currentUser();
      this.selectedOwnerKey.set('');
    });
  }

  @HostListener('document:keydown.escape')
  onEscape(): void {
    this.cancelled.emit(undefined);
  }

  confirmLeave(): void {
    this.confirmed.emit(
      this.selectedOwnerKey()
        ? { nextOwnerKey: this.selectedOwnerKey() }
        : {}
    );
  }

  roomMemberKey(member: RoomMember): string {
    return member.oderId || member.id;
  }

  roleLabel(member: RoomMember): string {
    switch (member.role) {
      case 'host':
        return this.appI18n.instant('shared.leaveServer.roles.owner');
      case 'admin':
        return this.appI18n.instant('shared.leaveServer.roles.admin');
      case 'moderator':
        return this.appI18n.instant('shared.leaveServer.roles.moderator');
      default:
        return this.appI18n.instant('shared.leaveServer.roles.member');
    }
  }
}
