import { Component, Inject } from '@angular/core';
import { DossierState } from '@red/domain';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { FormBuilder } from '@angular/forms';
import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker';
import { combineLatest, firstValueFrom } from 'rxjs';
import { DossierStatesService } from '@services/entity-services/dossier-states.service';
import { IconButtonTypes, LoadingService, Toaster } from '@iqser/common-ui';
import { ActiveDossiersService } from '@services/dossiers/active-dossiers.service';
import { ArchivedDossiersService } from '@services/dossiers/archived-dossiers.service';

export interface ConfirmDeleteDossierStateDialogData {
    readonly toBeDeletedState: DossierState;
    readonly otherStates: DossierState[];
    readonly dossierCount: number;
}

@Component({
    templateUrl: './confirm-delete-dossier-state-dialog.component.html',
    styleUrls: ['./confirm-delete-dossier-state-dialog.component.scss'],
})
export class ConfirmDeleteDossierStateDialogComponent {
    readonly iconButtonTypes = IconButtonTypes;
    readonly form = this.#form;
    readonly translateArgs = {
        name: this.data.toBeDeletedState.name,
        count: this.data.dossierCount,
    };

    constructor(
        private readonly _formBuilder: FormBuilder,
        private readonly _loadingService: LoadingService,
        private readonly _toaster: Toaster,
        private readonly _dossierStatesService: DossierStatesService,
        private readonly _dialogRef: MatDialogRef<ConfirmDeleteDossierStateDialogComponent>,
        private readonly _activeDossiersService: ActiveDossiersService,
        private readonly _archivedDossiersService: ArchivedDossiersService,
        @Inject(MAT_DIALOG_DATA) readonly data: ConfirmDeleteDossierStateDialogData,
    ) {}

    get label(): string {
        return this.#replaceDossierStatusId ? _('confirm-delete-dossier-state.delete-replace') : _('confirm-delete-dossier-state.delete');
    }

    get #replaceDossierStatusId(): string {
        return this.form.controls.replace.value ? this.form.controls.replaceDossierStatusId.value : undefined;
    }

    get #form() {
        return this._formBuilder.group({
            replace: [false],
            replaceDossierStatusId: [null],
        });
    }

    async save() {
        this._loadingService.start();

        await this._dossierStatesService.deleteState(this.data.toBeDeletedState, this.#replaceDossierStatusId);
        await firstValueFrom(combineLatest([this._activeDossiersService.loadAll(), this._archivedDossiersService.loadAll()]));

        this._toaster.success(_('confirm-delete-dossier-state.success'));
        this._dialogRef.close();
        this._loadingService.stop();
    }
}
