import { Component, OnInit } from '@angular/core';
import { CircleButtonComponent, IconButtonComponent, IqserDialogComponent, UploadFileComponent } from '@iqser/common-ui';
import { FileAttributeEncodingTypes, IComponentMapping } from '@red/domain';
import { FormBuilder, ReactiveFormsModule, UntypedFormGroup, Validators } from '@angular/forms';
import { TranslateModule } from '@ngx-translate/core';
import { NgForOf, NgIf } from '@angular/common';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatDialogModule } from '@angular/material/dialog';
import { MatOption } from '@angular/material/autocomplete';
import { MatSelect, MatSelectTrigger } from '@angular/material/select';
import { fileAttributeEncodingTypesTranslations } from '@translations/file-attribute-encoding-types-translations';
import { firstValueFrom } from 'rxjs';
import { ComponentMappingsService } from '@services/entity-services/component-mappings.service';
import { MatTooltip } from '@angular/material/tooltip';

interface DialogData {
    dossierTemplateId: string;
    mapping: IComponentMapping;
}

interface DialogResult {
    id: string;
    name: string;
    file: Blob;
    encoding: string;
    delimiter: string;
    quoteChar: string;
    fileName?: string;
}

@Component({
    templateUrl: './add-edit-component-mapping-dialog.component.html',
    styleUrls: ['./add-edit-component-mapping-dialog.component.scss'],
    standalone: true,
    imports: [
        TranslateModule,
        ReactiveFormsModule,
        NgIf,
        MatFormFieldModule,
        NgForOf,
        CircleButtonComponent,
        MatDialogModule,
        MatOption,
        MatSelectTrigger,
        MatSelect,
        IconButtonComponent,
        UploadFileComponent,
        MatTooltip,
    ],
})
export class AddEditComponentMappingDialogComponent
    extends IqserDialogComponent<AddEditComponentMappingDialogComponent, DialogData, DialogResult>
    implements OnInit
{
    protected readonly encodingTypeOptions = Object.keys(FileAttributeEncodingTypes);
    protected readonly translations = fileAttributeEncodingTypesTranslations;
    activeFile: File;
    form!: UntypedFormGroup;

    constructor(
        private readonly _formBuilder: FormBuilder,
        private readonly _componentMappingService: ComponentMappingsService,
    ) {
        super();
        this.form = this.#getForm();
    }

    async ngOnInit() {
        if (this.data.mapping?.fileName) {
            this.activeFile = { name: this.data.mapping.fileName } as File;
            const fileContent = await firstValueFrom(
                this._componentMappingService.getComponentMappingFile(this.data.dossierTemplateId, this.data.mapping.id),
            );
            const file = new Blob([fileContent.body as Blob], { type: 'text/csv' });
            this.form.get('file').setValue(file);
            this.initialFormValue = this.form.getRawValue();
            this.#disableEncodingAndQuoteCharAndDelimiter();
        }
    }

    changeFile(file: File) {
        this.form.get('file').setValue(file);
        this.form.get('fileName').setValue(file?.name);
        this.#enableEncodingAndQuoteCharAndDelimiter();
    }

    save() {
        this.dialogRef.close({ ...this.data.mapping, ...this.form.getRawValue() });
    }

    #getForm(): UntypedFormGroup {
        return this._formBuilder.group({
            name: [this.data?.mapping?.name, Validators.required],
            file: [null, Validators.required],
            fileName: [this.data?.mapping?.fileName, Validators.required],
            encoding: this.encodingTypeOptions.find(e => e === this.data?.mapping?.encoding) ?? this.encodingTypeOptions[0],
            delimiter: [this.data?.mapping?.delimiter ?? ',', Validators.required],
            quoteChar: [this.data?.mapping?.quoteChar ?? '"', Validators.required],
        });
    }

    #disableEncodingAndQuoteCharAndDelimiter() {
        this.form.get('encoding').disable();
        this.form.get('delimiter').disable();
        this.form.get('quoteChar').disable();
    }

    #enableEncodingAndQuoteCharAndDelimiter() {
        this.form.get('encoding').enable();
        this.form.get('delimiter').enable();
        this.form.get('quoteChar').enable();
    }
}
