import { NgIf } from '@angular/common';
import { Component, Input, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { CircleButtonComponent, IqserHelpModeModule, LoadingService } from '@iqser/common-ui';
import { TenantsService } from '@iqser/common-ui/lib/tenants';
import { getCurrentUser } from '@iqser/common-ui/lib/users';
import { TranslateModule } from '@ngx-translate/core';
import { DOSSIER_TEMPLATE_ID, type User } from '@red/domain';
import { DossierTemplatesService } from '@services/dossier-templates/dossier-templates.service';
import { firstValueFrom } from 'rxjs';
import { AdminDialogService } from '../../../services/admin-dialog.service';

@Component({
    selector: 'redaction-dossier-template-actions',
    templateUrl: './dossier-template-actions.component.html',
    styleUrls: ['./dossier-template-actions.component.scss'],
    standalone: true,
    imports: [NgIf, IqserHelpModeModule, CircleButtonComponent, TranslateModule],
})
export class DossierTemplateActionsComponent implements OnInit {
    @Input() dossierTemplateId: string;

    readonly currentUser = getCurrentUser<User>();

    constructor(
        private readonly _router: Router,
        private readonly _route: ActivatedRoute,
        private readonly _loadingService: LoadingService,
        private readonly _dialogService: AdminDialogService,
        private readonly _tenantsService: TenantsService,
        private readonly _dossierTemplatesService: DossierTemplatesService,
    ) {}

    ngOnInit() {
        this.dossierTemplateId ??= this._route.snapshot.paramMap.get(DOSSIER_TEMPLATE_ID);
    }

    openEditCloneDossierTemplateDialog(clone: boolean = false) {
        this._dialogService.openDialog('addEditCloneDossierTemplate', { dossierTemplateId: this.dossierTemplateId, clone });
    }

    openDeleteDossierTemplateDialog() {
        this._dialogService.openDialog('confirm', null, async () => {
            this._loadingService.start();

            const success = await firstValueFrom(this._dossierTemplatesService.delete([this.dossierTemplateId]));
            if (success) {
                await this._router.navigate([this._tenantsService.activeTenantId, 'main', 'admin']);
            }

            this._loadingService.stop();
        });
    }
}
