import {
  Component,
  HostListener,
  computed,
  effect,
  input,
  output,
  signal
} from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import {
  Room,
  RoomMember,
  User
} from '../../../shared-kernel';

export interface LeaveServerDialogResult {
  nextOwnerKey?: string;
}

@Component({
  selector: 'app-leave-server-dialog',
  standalone: true,
  imports: [CommonModule, FormsModule],
  templateUrl: './leave-server-dialog.component.html'
})
export class LeaveServerDialogComponent {
  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 'Owner';
      case 'admin':
        return 'Admin';
      case 'moderator':
        return 'Moderator';
      default:
        return 'Member';
    }
  }
}
