import { NgIf } from '@angular/common';
import { Component, Input, OnInit } from '@angular/core';
import { ActivatedRoute, Router, RouterLink } from '@angular/router';
import { CircleButtonComponent, LoadingService } from '@iqser/common-ui';
import { getCurrentUser } from '@iqser/common-ui/lib/users';
import { TranslateModule } from '@ngx-translate/core';
import { DOSSIER_TEMPLATE_ID, DossierTemplate, 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, CircleButtonComponent, TranslateModule, RouterLink],
})
export class DossierTemplateActionsComponent implements OnInit {
    @Input() dossierTemplateId: string;

    readonly currentUser = getCurrentUser<User>();
    dossierTemplate: DossierTemplate;

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

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

    openCloneDossierTemplateDialog() {
        this._dialogService.openDialog('addCloneDossierTemplate', { dossierTemplateId: this.dossierTemplateId });
    }

    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(['main', 'admin']);
            }

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