import { Component, Input, OnChanges, SimpleChanges, ViewChild } from '@angular/core';
import { Action, ActionTypes, Dossier, File } from '@red/domain';
import { CircleButtonType, IqserDialog, Toaster } from '@iqser/common-ui';
import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker';
import { FileDownloadService } from '@upload-download/services/file-download.service';
import { PermissionsService } from '@services/permissions.service';
import { MatMenuTrigger } from '@angular/material/menu';
import { DownloadDialogComponent } from '@shared/dialogs/download-dialog/download-dialog.component';
import { IqserTooltipPosition, trackByFactory } from '@iqser/common-ui/lib/utils';
import { TenantsService } from '@iqser/common-ui/lib/tenants';

@Component({
    selector: 'redaction-expandable-file-actions',
    templateUrl: './expandable-file-actions.component.html',
    styleUrls: ['./expandable-file-actions.component.scss'],
})
export class ExpandableFileActionsComponent implements OnChanges {
    @Input({ required: true }) actions: Action[];
    @Input() maxWidth: number;
    @Input() minWidth: number;
    @Input() buttonType: CircleButtonType;
    @Input() tooltipPosition: IqserTooltipPosition;
    @Input() helpModeKeyPrefix: 'dossier' | 'editor';
    @Input() isDossierOverviewWorkflow = false;

    displayedButtons: Action[];
    hiddenButtons: Action[];
    expanded = false;

    @ViewChild(MatMenuTrigger) readonly matMenu: MatMenuTrigger;
    readonly trackBy = trackByFactory();

    constructor(
        private readonly _fileDownloadService: FileDownloadService,
        private readonly _tenantsService: TenantsService,
        private readonly _toaster: Toaster,
        private readonly _permissionsService: PermissionsService,
        private readonly _dialog: IqserDialog,
    ) {}

    ngOnChanges(changes: SimpleChanges) {
        if (changes.actions || changes.maxWidth || changes.minWidth) {
            let count = 0;
            if (this.maxWidth) {
                count = Math.floor(this.maxWidth / 36) || 1;
            } else if (this.minWidth <= 850) {
                count = Math.floor(this.minWidth / (this.actions.length * 15)) || 1;
                if (this.minWidth <= 450) {
                    this.displayedButtons = [];
                    this.hiddenButtons = [...this.actions];
                    return;
                }
            } else {
                this.displayedButtons = [...this.actions];
                this.hiddenButtons = [];
                return;
            }

            if (count >= this.actions.length) {
                this.displayedButtons = [...this.actions];
                this.hiddenButtons = [];
            } else {
                this.displayedButtons = this.actions.slice(0, count - 1);
                this.hiddenButtons = this.actions.slice(count - 1);
            }
        }

        if (changes.actions) {
            // Patch download button
            const downloadBtn = this.actions.find(btn => btn.type === ActionTypes.downloadBtn);
            if (downloadBtn) {
                downloadBtn.action = () => this.#downloadFiles(downloadBtn.files, downloadBtn.dossier);
                downloadBtn.disabled = !this._permissionsService.canDownloadFiles(downloadBtn.files, downloadBtn.dossier);
            }
        }
    }

    helpModeKey(action: Action) {
        return action.helpModeKey
            ? `${this.helpModeKeyPrefix}${this.isDossierOverviewWorkflow ? '_workflow' : ''}_${action.helpModeKey}`
            : '';
    }

    onButtonClick(button: Action, $event: MouseEvent) {
        button.action($event);
        this.matMenu.closeMenu();
    }

    async #downloadFiles(files: File[], dossier: Dossier) {
        const ref = this._dialog.openDefault(DownloadDialogComponent, {
            data: { dossier, files },
        });
        const result = await ref.result();
        if (!result) {
            return;
        }

        await this._fileDownloadService.downloadFiles({
            dossierId: dossier.id,
            fileIds: files.map(f => f.id),
            ...result,
        });
        this._toaster.info(_('download-status.queued'), {
            params: { downloadHref: `/ui/${this._tenantsService.activeTenantId}/main/downloads` },
        });
    }
}
