import { Component, computed } from '@angular/core';
import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker';
import { LoadingService, Toaster } from '@iqser/common-ui';
import { getCurrentUser } from '@iqser/common-ui/lib/users';
import { File, User } from '@red/domain';
import { FilesService } from '@services/files/files.service';
import { PermissionsService } from '@services/permissions.service';
import { workflowFileStatusTranslations } from '@translations/file-status-translations';
import { UserService } from '@users/user.service';
import { moveElementInArray } from '@utils/functions';
import { FileAssignService } from '../../../shared-dossiers/services/file-assign.service';
import { FilePreviewStateService } from '../../services/file-preview-state.service';

@Component({
    selector: 'redaction-user-management',
    templateUrl: './user-management.component.html',
    styleUrls: ['./user-management.component.scss'],
})
export class UserManagementComponent {
    protected readonly _canAssignToSelf = computed(() => this.permissionsService.canAssignToSelf(this.state.file(), this.state.dossier()));
    protected readonly _canAssignUser = computed(() => this.permissionsService.canAssignUser(this.state.file(), this.state.dossier()));
    protected readonly _canUnassignUser = computed(() => this.permissionsService.canUnassignUser(this.state.file(), this.state.dossier()));
    protected readonly _canAssignOrUnassign = computed(() => this._canAssignUser() || this._canUnassignUser());
    protected readonly _canAssign = computed(() => this._canAssignToSelf() || this._canAssignOrUnassign());
    protected readonly _canAssignReviewer = computed(() => this._canAssignUser() && !this.state.file().assignee);
    protected readonly _usersOptions = computed(() => {
        const file = this.state.file();
        const dossier = this.state.dossier();
        const canUnassignUser = this._canUnassignUser();
        const unassignUser = canUnassignUser && file.assignee ? [undefined] : [];
        return file.isUnderApproval
            ? this.#customSort([...dossier.approverIds, ...unassignUser])
            : this.#customSort([...dossier.memberIds, ...unassignUser]);
    });
    protected readonly _currentUserId = getCurrentUser().id;
    readonly translations = workflowFileStatusTranslations;
    readonly statusBarConfig = computed(() => [{ length: 1, color: this.state.file().workflowStatus }]);
    readonly assignTooltip = computed(() => {
        const file = this.state.file();
        return file.isUnderApproval
            ? _('dossier-overview.assign-approver')
            : file.assignee
            ? _('file-preview.change-reviewer')
            : _('file-preview.assign-reviewer');
    });
    editingReviewer = false;

    constructor(
        readonly fileAssignService: FileAssignService,
        readonly permissionsService: PermissionsService,
        readonly userService: UserService,
        readonly filesService: FilesService,
        readonly toaster: Toaster,
        readonly loadingService: LoadingService,
        readonly state: FilePreviewStateService,
    ) {}

    async assignReviewer(file: File, user: User | string) {
        const assigneeId = typeof user === 'string' ? user : user?.id;

        this.loadingService.start();

        if (!assigneeId || file.isApproved) {
            await this.filesService.setAssignee(file, assigneeId);
        } else if (file.isNew || file.isUnderReview) {
            await this.filesService.setReviewer(file, assigneeId);
        } else {
            await this.filesService.setUnderApproval(file, assigneeId);
        }

        this.loadingService.stop();

        const translateParams = { reviewerName: this.userService.getName(assigneeId), filename: file.filename };
        this.toaster.success(_('assignment.reviewer'), { params: translateParams });
        this.editingReviewer = false;
    }

    #customSort(ids: string[]) {
        let sorted = [...ids].sort((a, b) => this.userService.getName(a).localeCompare(this.userService.getName(b)));
        sorted = moveElementInArray(sorted, this._currentUserId, 0);
        if (sorted.includes(undefined)) {
            sorted = moveElementInArray(sorted, undefined, 1);
        }
        return sorted;
    }
}
