import { Component, Inject, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import {
  MAT_DIALOG_DATA,
  MatDialog,
  MatDialogRef,
} from '@angular/material/dialog';
import {
  DetailsFormWorkflow,
  RequestFormWorkflow,
  RegisterWorkflowRequest,
  ResponseDataWorkflow,
} from '../../../../interfaces/process-managementv/workflow-management.interface';
import {
  ResourcesService,
  ResponseData,
} from '../../../../services/resources.service';
import { InternationalizationService } from '../../../../services/internationalization/internationalization.service';
import { ProcessManagementService } from '../../../../services/process-management/process-management.service';
import { lastValueFrom } from 'rxjs';
import { HttpErrorResponse } from '@angular/common/http';
import { AlertComponent } from '../../../resources/dialogs/alert/alert.component';

@Component({
  selector: 'app-form-workflow',
  templateUrl: './form-workflow.component.html',
  styleUrl: './form-workflow.component.css',
  standalone: false,
})
export class FormWorkflowComponent implements OnInit {
  public titleForm: string;
  public formGroup: FormGroup;
  public isLoading: boolean;
  public idWorkflow!: string;
  public isEditMode: boolean;

  constructor(
    @Inject(MAT_DIALOG_DATA) public detailsFormWorkflow: DetailsFormWorkflow,
    public resourcesService: ResourcesService,
    public interService: InternationalizationService,
    private _dialog: MatDialog,
    private _dialogRef: MatDialogRef<boolean>,
    private _processManagementService: ProcessManagementService
  ) {
    this.isEditMode = this.detailsFormWorkflow.type === 'UPD';
    this.titleForm = this.isEditMode
      ? this.interService.get('modificacion_flujo_trabajo')
      : this.interService.get('registro_flujo_trabajo');
    this.isLoading = false;
    this.formGroup = this._createFormGroup();
  }

  private _createFormGroup() {
    const formControls: any = {
      NOMBRE_WORKFLOW: new FormControl(null, Validators.required),
      DESCRIPCION: new FormControl(null, Validators.required),
    };

    if (this.isEditMode) {
      formControls.COMENTARIO_CAMBIO = new FormControl(
        null,
        Validators.required
      );
    }

    return new FormGroup(formControls);
  }

  async ngOnInit() {
    if (this.isEditMode && this.detailsFormWorkflow.idWorkflow !== undefined) {
      this.idWorkflow = this.detailsFormWorkflow.idWorkflow.toString();
      await this.getWorkflowById();
    }
  }

  private async getWorkflowById() {
    this.isLoading = true;
    const user: string = this.resourcesService.getUser();
    const line: number = this.resourcesService.getLineNumber();
    await lastValueFrom(
      this._processManagementService.getWorkflowById(
        this.idWorkflow,
        user,
        line
      )
    ).then(
      (responseData: ResponseDataWorkflow) => {
        if (
          !responseData.error &&
          Object.keys(responseData.response).length > 0
        ) {
          this.formGroup.controls['NOMBRE_WORKFLOW'].setValue(
            responseData.response.NOMBRE_WORKFLOW
          );
          this.formGroup.controls['DESCRIPCION'].setValue(
            responseData.response.DESCRIPCION
          );
        } else if (
          !responseData.error &&
          Object.keys(responseData.response).length === 0
        ) {
          this.resourcesService.openSnackBar(
            this.interService.get('no_pudo_encontrar_informacion')
          );
          this._dialogRef.close(false);
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
          this._dialogRef.close(false);
        }
      },
      async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse);
        if (response !== null && response.reload) {
          await this.getWorkflowById();
        }
      }
    );
    this.isLoading = false;
  }

  public async save() {
    if (this.isEditMode) {
      this._dialog
        .open(AlertComponent, {
          disableClose: true,
          data: {
            title: this.interService.get('confirmacion'),
            description: this.interService.get('update_description_alert'),
            icon: `warning`,
            btnCancelar: this.interService.get('cancelar'),
            btnAceptar: this.interService.get('aceptar'),
          },
        })
        .afterClosed()
        .subscribe(async (result) => {
          if (result) {
            await this._updateWorkflow();
          }
        });
    } else {
      await this._registerWorkflow();
    }
  }

  private async _updateWorkflow() {
    this.isLoading = true;
    const requestFormWorkflow: RequestFormWorkflow =
      this._createRequestFormWorkflow();
    await lastValueFrom(
      this._processManagementService.updateWorkflow(
        this.idWorkflow,
        requestFormWorkflow
      )
    ).then(
      (responseData: ResponseData) => {
        if (!responseData.error) {
          this.resourcesService.openSnackBar(
            this.interService.get('modificacion_exitoso')
          );
          this._dialogRef.close(true);
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      },
      async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse);
        if (response !== null && response.reload) {
          await this._updateWorkflow();
        }
      }
    );
    this.isLoading = false;
  }

  private async _registerWorkflow() {
    this.isLoading = true;
    const registerRequest: RegisterWorkflowRequest = {
      NOMBRE_WORKFLOW: this.formGroup.controls['NOMBRE_WORKFLOW'].value
        .toString()
        .trim(),
      DESCRIPCION: this.formGroup.controls['DESCRIPCION'].value
        .toString()
        .trim(),
      USUARIO: this.resourcesService.getUser(),
      NUMERO_LINEA: this.resourcesService.getLineNumber(),
    };

    await lastValueFrom(
      this._processManagementService.registerNewWorkflow(registerRequest)
    ).then(
      (responseData: ResponseData) => {
        if (!responseData.error) {
          this.resourcesService.openSnackBar(
            this.interService.get('registro_exitoso')
          );
          this._dialogRef.close(true);
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      },
      async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse);
        if (response !== null && response.reload) {
          await this._registerWorkflow();
        }
      }
    );
    this.isLoading = false;
  }

  private _createRequestFormWorkflow(): RequestFormWorkflow {
    let nombreWorkflow = this.formGroup.controls['NOMBRE_WORKFLOW'].value;
    nombreWorkflow = nombreWorkflow.toString().trim();

    let descripcion = this.formGroup.controls['DESCRIPCION'].value;
    descripcion = descripcion.toString().trim();

    let comentarioCambio = this.formGroup.controls['COMENTARIO_CAMBIO'].value;
    comentarioCambio = comentarioCambio.toString().trim();

    const requestFormWorkflow: RequestFormWorkflow = {
      NOMBRE_WORKFLOW: nombreWorkflow,
      DESCRIPCION: descripcion,
      COMENTARIO_CAMBIO: comentarioCambio,
      USUARIO: this.resourcesService.getUser(),
      NUMERO_LINEA: this.resourcesService.getLineNumber(),
    };

    return requestFormWorkflow;
  }
}
