import {Component, computed, effect, inject, input, output, signal} from '@angular/core';
import {ChatChannel} from '@pages/altitude/chat/objects/chat-channel.object';
import {CircleSvgComponent} from '@pages/altitude/chat/svg/circle.svg';
import {NameFormatService} from '@pages/altitude/chat/service/name-format.service';
import {ColoredNameSegment} from '@pages/altitude/chat/objects/colored-name-segment.object';

@Component({
  selector: 'app-channel-list',
  imports: [
    CircleSvgComponent
  ],
  templateUrl: './channel-list.component.html',
  styleUrl: './channel-list.component.scss'
})
export class ChannelListComponent {
  protected readonly nameFormatService: NameFormatService = inject(NameFormatService);
  public readonly channels = input.required<ChatChannel[]>();
  public readonly selectedChannel = input.required<ChatChannel | null>();
  public readonly selectedChannelChange = output<ChatChannel>();

  protected readonly collapsedGroups = signal<Set<string>>(new Set());

  protected toggleGroup(type: string) {
    const next = new Set(this.collapsedGroups());
    if (next.has(type)) {
      next.delete(type);
    } else {
      next.add(type);
    }
    this.collapsedGroups.set(next);
  }

  protected readonly groupedChannels = computed(() => {
    const channels = this.channels();
    const groups: { type: ChatChannel['type'], channels: ChatChannel[] }[] = [];
    const types: ChatChannel['type'][] = ['SERVER', 'DM', 'PARTY', 'GAC', 'SPY'];

    for (const type of types) {
      const typeChannels = channels.filter(c => c.type === type);
      if (typeChannels.length > 0) {
        groups.push({type, channels: typeChannels});
      }
    }

    return groups;
  });

  constructor() {
    effect(() => {
      const chatChannels = this.channels();
      if (this.selectedChannel() === null && chatChannels.length > 0) {
        this.selectedChannelChange.emit(chatChannels[0]);
      }
    });
  }

  protected getDisplayName(chatChannel: ChatChannel): ColoredNameSegment[] {
    return this.nameFormatService.getDisplayName(chatChannel);
  }
}
