import { HttpStatusCode } from '@angular/common/http';
import { Component, Inject } from '@angular/core';
import { ReactiveFormsModule, Validators } from '@angular/forms';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker';
import { BaseDialogComponent, CircleButtonComponent, getConfig, IconButtonComponent, SaveOptions } from '@iqser/common-ui';
import { DossierTemplate } from '@red/domain';
import { DossierTemplatesService } from '@services/dossier-templates/dossier-templates.service';
import { Router } from '@angular/router';
import { TranslateModule } from '@ngx-translate/core';

export interface CloneTemplateData {
    dossierTemplateId?: string;
}

@Component({
    templateUrl: './add-clone-dossier-template-dialog.component.html',
    styleUrls: ['./add-clone-dossier-template-dialog.component.scss'],
    standalone: true,
    imports: [TranslateModule, ReactiveFormsModule, IconButtonComponent, CircleButtonComponent],
})
export class AddCloneDossierTemplateDialogComponent extends BaseDialogComponent {
    readonly dossierTemplate?: DossierTemplate;
    readonly isDocumine = getConfig().IS_DOCUMINE;
    readonly translateParams: { type: string; dossierTemplateName?: string };

    constructor(
        private readonly _dossierTemplatesService: DossierTemplatesService,
        private readonly _router: Router,
        protected readonly _dialogRef: MatDialogRef<AddCloneDossierTemplateDialogComponent>,
        @Inject(MAT_DIALOG_DATA) readonly data: CloneTemplateData,
    ) {
        super(_dialogRef);
        this.dossierTemplate = this._dossierTemplatesService.find(this.data.dossierTemplateId);

        this.translateParams = {
            type: this.dossierTemplate ? 'clone' : 'create',
            dossierTemplateName: this.dossierTemplate?.name,
        };

        this.form = this.#getForm();
        this.initialFormValue = this.form.getRawValue();
    }

    override get disabled(): boolean {
        // Ignore 'changed' value, doesn't make sense in this context
        return !this.valid || this._hasErrors();
    }

    async save(options?: SaveOptions): Promise<void> {
        let dossierTemplate: DossierTemplate;
        this._loadingService.start();
        const body = {
            ...this.dossierTemplate,
            ...this.form.getRawValue(),
        };
        try {
            if (this.dossierTemplate) {
                dossierTemplate = await this._dossierTemplatesService.clone(this.dossierTemplate.id, body);
            } else {
                dossierTemplate = await this._dossierTemplatesService.createOrUpdate(body);
            }
            if (options?.nextAction) {
                await this._router.navigate([dossierTemplate.routerLink]);
            }
            this._dialogRef.close(true);
        } catch (error) {
            if (error.status === HttpStatusCode.Conflict) {
                this._toaster.error(_('add-edit-clone-dossier-template.error.conflict'), { error });
            } else {
                this._toaster.rawError(error.error.message);
            }
        }
        this._loadingService.stop();
    }

    #getForm() {
        return this._formBuilder.group({
            name: [this.dossierTemplate ? this.#getCloneName(this.dossierTemplate) : undefined, Validators.required],
            description: [this.dossierTemplate?.description],
        });
    }

    #getCloneName(initialTemplate: DossierTemplate): string {
        const templateName = initialTemplate.name.trim();
        let nameOfClonedTemplate: string = templateName.split('Copy of ').filter(n => n)[0];
        nameOfClonedTemplate = nameOfClonedTemplate.split(/\(\s*\d+\s*\)$/)[0].trim();
        const allTemplatesNames = this._dossierTemplatesService.all.map(t => t.name);

        let clonesCount = 0;
        for (const name of allTemplatesNames) {
            const splitName = name.split(nameOfClonedTemplate);
            const suffixRegExp = new RegExp(/^\(\s*\d+\s*\)$/);
            if (splitName[0] === 'Copy of ' && (splitName[1].trim().match(suffixRegExp) || splitName[1] === '')) {
                clonesCount++;
            }
        }

        if (clonesCount >= 1) {
            return `Copy of ${nameOfClonedTemplate} (${clonesCount})`;
        }
        return `Copy of ${nameOfClonedTemplate}`;
    }
}
