import { Component, ElementRef, Input, OnInit, QueryList, ViewChildren } from '@angular/core';
import { UntypedFormBuilder, UntypedFormGroup } from '@angular/forms';
import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker';
import { IconButtonTypes, LoadingService, Toaster } from '@iqser/common-ui';
import { Dossier, DossierAttributeConfigType, DossierAttributeConfigTypes, DossierAttributeWithValue } from '@red/domain';
import { DossierAttributesService } from '@services/entity-services/dossier-attributes.service';
import { PermissionsService } from '@services/permissions.service';
import dayjs from 'dayjs';
import { firstValueFrom } from 'rxjs';
import { EditDossierSaveResult, EditDossierSectionInterface } from '../edit-dossier-section.interface';

@Component({
    selector: 'redaction-edit-dossier-attributes',
    templateUrl: './edit-dossier-attributes.component.html',
    styleUrls: ['./edit-dossier-attributes.component.scss'],
})
export class EditDossierAttributesComponent implements EditDossierSectionInterface, OnInit {
    @ViewChildren('fileInput') private _fileInputs: QueryList<ElementRef>;
    readonly iconButtonTypes = IconButtonTypes;
    readonly dossierAttributeConfigTypes = DossierAttributeConfigTypes;
    @Input() dossier: Dossier;
    customAttributes: DossierAttributeWithValue[] = [];
    imageAttributes: DossierAttributeWithValue[] = [];
    attributes: DossierAttributeWithValue[] = [];
    form: UntypedFormGroup;

    constructor(
        private readonly _permissionsService: PermissionsService,
        private readonly _dossierAttributesService: DossierAttributesService,
        private readonly _loadingService: LoadingService,
        private readonly _formBuilder: UntypedFormBuilder,
        private readonly _toaster: Toaster,
    ) {}

    get changed() {
        for (const attr of this.attributes) {
            if (this.isSpecificType(attr, this.dossierAttributeConfigTypes.DATE) && attr.value) {
                if (!dayjs(attr.value).isSame(dayjs(this.currentAttrValue(attr)), 'day')) {
                    return true;
                }
            } else if (this._parseAttrValue(attr.value) !== this._parseAttrValue(this.currentAttrValue(attr))) {
                return true;
            }
        }

        return false;
    }

    get disabled(): boolean {
        return !this._permissionsService.isOwner(this.dossier) || this.dossier.isArchived;
    }

    get valid(): boolean {
        return !!this.form?.valid;
    }

    async ngOnInit() {
        this._loadingService.start();
        await this._loadAttributes();
        this.form = this._getForm();
        this._loadingService.stop();
    }

    async save(): EditDossierSaveResult {
        const dossierAttributeList = this.attributes.map(attr => ({
            dossierAttributeConfigId: attr.id,
            value:
                this.isSpecificType(attr, DossierAttributeConfigTypes.DATE) && !!this.currentAttrValue(attr)
                    ? dayjs(this.currentAttrValue(attr)).format('YYYY-MM-DD')
                    : this.currentAttrValue(attr),
        }));
        try {
            await firstValueFrom(this._dossierAttributesService.setAttributes(this.dossier, dossierAttributeList));
            await firstValueFrom(this._dossierAttributesService.loadAll(this.dossier.dossierTemplateId));
            await this._loadAttributes();
            return { success: true };
        } catch (error) {
            this._toaster.error(_('edit-dossier-dialog.attributes.error.generic'));
            return { success: false };
        }
    }

    fileInputClick(attr: DossierAttributeWithValue) {
        this._getFileInputById(attr.id).nativeElement.click();
    }

    isSpecificType(attr: DossierAttributeWithValue, type: DossierAttributeConfigType): boolean {
        return attr.type === type;
    }

    async uploadImage($event, attr: DossierAttributeWithValue) {
        const toBase64 = file =>
            new Promise((resolve, reject) => {
                const reader = new FileReader();
                reader.readAsDataURL(file);
                reader.onload = () => resolve(reader.result);
                reader.onerror = error => reject(error);
            });

        const image = $event.target.files[0];
        const result = await toBase64(image);
        this.form.patchValue({
            [attr.id]: result,
        });
        this._getFileInputById(attr.id).nativeElement.value = null;
    }

    revert() {
        this.form = this._getForm();
    }

    currentAttrValue(attr: DossierAttributeWithValue): string {
        return this.form.get(attr.id).value;
    }

    deleteAttr(attr: DossierAttributeWithValue) {
        this.form.patchValue({
            [attr.id]: null,
        });
    }

    private _getFileInputById(id: string): ElementRef {
        return this._fileInputs.find(el => el.nativeElement.id === id);
    }

    private _parseAttrValue(value: any) {
        return [null, undefined, ''].includes(value) ? undefined : value;
    }

    private async _loadAttributes() {
        this.attributes = await this._dossierAttributesService.getWithValues(this.dossier);
        this.customAttributes = this.attributes.filter(attr => !this.isSpecificType(attr, this.dossierAttributeConfigTypes.IMAGE));
        this.imageAttributes = this.attributes.filter(attr => this.isSpecificType(attr, this.dossierAttributeConfigTypes.IMAGE));
    }

    private _getForm(): UntypedFormGroup {
        const controlsConfig = {};
        for (const attribute of this.attributes) {
            controlsConfig[attribute.id] = [{ value: attribute.value, disabled: this.disabled }];
        }
        return this._formBuilder.group(controlsConfig);
    }
}
