import { Component, ElementRef, EventEmitter, inject, Input, OnChanges, Output, ViewChild } from '@angular/core';
import { CircleButtonTypes } from '@iqser/common-ui';
import { DossiersDialogService } from '../../../shared-dossiers/services/dossiers-dialog.service';
import { Roles } from '@users/roles';
import { User } from '@red/domain';
import { UserService } from '@users/user.service';
import { getCurrentUser } from '@iqser/common-ui/lib/users';
import { List } from '@iqser/common-ui/lib/utils';

@Component({
    selector: 'redaction-team-members',
    templateUrl: './team-members.component.html',
    styleUrls: ['./team-members.component.scss'],
})
export class TeamMembersComponent implements OnChanges {
    readonly circleButtonTypes = CircleButtonTypes;
    readonly roles = Roles;
    readonly currentUser = getCurrentUser<User>();
    readonly userService = inject(UserService);

    @Input() memberIds: List;
    @Input() perLine: number;
    @Input() dossierId: string;
    @Input() canAdd = true;
    @Input() largeSpacing = false;
    @Input() canRemove = false;
    @Input() unremovableMembers: string[] = [];
    @Output() remove = new EventEmitter<string>();

    @ViewChild('container', { static: true }) readonly container: ElementRef;

    expandedTeam = false;

    constructor(private readonly _dialogService: DossiersDialogService) {}

    get maxTeamMembersBeforeExpand(): number {
        return this.perLine - (this.canAdd ? 1 : 0);
    }

    get displayedMembers(): List {
        return this.expandedTeam || !this.overflowCount ? this.memberIds : this.memberIds.slice(0, this.maxTeamMembersBeforeExpand - 1);
    }

    get overflowCount() {
        return this.memberIds.length > this.maxTeamMembersBeforeExpand ? this.memberIds.length - (this.maxTeamMembersBeforeExpand - 1) : 0;
    }

    ngOnChanges() {
        this.memberIds ??= [];
        this.memberIds = [...this.memberIds].sort((a, b) => this.userService.getName(a).localeCompare(this.userService.getName(b)));
    }

    toggleExpandedTeam() {
        this.expandedTeam = !this.expandedTeam;
    }

    canRemoveMember(userId: string) {
        return this.canRemove && !this.unremovableMembers.includes(userId);
    }

    openEditDossierDialog(): void {
        const data = { dossierId: this.dossierId, section: 'members' };
        this._dialogService.openDialog('editDossier', data);
    }
}
