import { NgForOf, NgIf } from '@angular/common';
import { Component, ElementRef, EventEmitter, inject, Input, OnChanges, Output, ViewChild } from '@angular/core';
import { MatIcon } from '@angular/material/icon';
import { CircleButtonComponent, CircleButtonTypes, IqserAllowDirective, largeDialogConfig } from '@iqser/common-ui';
import { getCurrentUser, InitialsAvatarComponent } from '@iqser/common-ui/lib/users';
import { List } from '@iqser/common-ui/lib/utils';
import { TranslateModule } from '@ngx-translate/core';
import { User } from '@red/domain';
import { Roles } from '@users/roles';
import { UserService } from '@users/user.service';
import { DossiersDialogService } from '../../../shared-dossiers/services/dossiers-dialog.service';

@Component({
    selector: 'redaction-team-members',
    templateUrl: './team-members.component.html',
    styleUrls: ['./team-members.component.scss'],
    standalone: true,
    imports: [NgForOf, InitialsAvatarComponent, NgIf, MatIcon, CircleButtonComponent, IqserAllowDirective, TranslateModule],
})
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);
    }

    async openEditDossierDialog() {
        const data = { dossierId: this.dossierId, section: 'members' };
        const editDossierDialogComponent = await import(
            '../../../shared-dossiers/dialogs/edit-dossier-dialog/edit-dossier-dialog.component'
        ).then(m => m.EditDossierDialogComponent);
        this._dialogService.open(editDossierDialogComponent, data, { ...largeDialogConfig, width: '98vw', maxWidth: '98vw' });
    }
}
