import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import {
  ChangeWorkflowStatusRequest,
  GetWorkflows,
  ResponseDataGetWorkflows,
  ResponseDataWorkflow,
  ResponseDataGetTaskByWorkflow,
} from '../../../interfaces/process-managementv/workflow-management.interface';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import {
  ResourcesService,
  ResponseData,
} from '../../../services/resources.service';
import { InternationalizationService } from '../../../services/internationalization/internationalization.service';
import { ProcessManagementService } from '../../../services/process-management/process-management.service';
import { MatDialog } from '@angular/material/dialog';
import { EncService } from '../../../services/enc.service';
import { lastValueFrom } from 'rxjs';
import { HttpErrorResponse } from '@angular/common/http';
import { AlertComponent } from '../../resources/dialogs/alert/alert.component';
import { FormWorkflowComponent } from './form-workflow/form-workflow.component';
import { RequestUserNumberLine } from '../../../interfaces/response-data';
import { ViewGraphicWorkflowComponent } from './view-graphic-workflow/view-graphic-workflow.component';
import { WorkflowDetailsComponent } from './workflow-details/workflow-details.component';
import { ChangeStatusWorkflowComponent } from './change-status-workflow/change-status-workflow.component';
import { WorkflowHistoryComponent } from './workflow-history/workflow-history.component';

import { Router } from '@angular/router';

@Component({
  selector: 'app-workflow-management',
  templateUrl: './workflow-management.component.html',
  styleUrl: './workflow-management.component.css',
  standalone: false,
})
export class WorkflowManagementComponent implements OnInit, AfterViewInit {
  public isLoading: boolean;
  public isLoadingForm: boolean;

  public dataSource: MatTableDataSource<GetWorkflows>;
  public displayedColumns: Array<string>;
  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;

  constructor(
    public resourcesService: ResourcesService,
    public interService: InternationalizationService,
    private _processManagementService: ProcessManagementService,
    private _dialog: MatDialog,
    private _encService: EncService,
    private _router: Router
  ) {
    this.isLoading = false;
    this.isLoadingForm = false;

    this.dataSource = new MatTableDataSource<GetWorkflows>();
    this.displayedColumns = [
      'ID_WORKFLOW',
      'SEGUIMIENTO',
      'NOMBRE_WORKFLOW',
      'DESCRIPCION',
      'MODULOS',
      'PREDETERMINADO',
      'VERSION',
      'ESTADO',
      'HISTORIAL',
      'ACCIONES',
    ];
  }

  async ngOnInit() {
    await this.getWorkflows();
  }

  public async getWorkflows() {
    this.isLoading = true;
    const user: string = this.resourcesService.getUser();
    const line: number = this.resourcesService.getLineNumber();
    await lastValueFrom(
      this._processManagementService.getWorkflows(user, line)
    ).then(
      (responseData: ResponseDataGetWorkflows) => {
        if (!responseData.error) {
          console.log(responseData);

          this.dataSource.data = responseData.response;
          this.dataSource.paginator = this.paginator;
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      },
      async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse);
        if (response !== null && response.reload) {
          await this.getWorkflows();
        }
      }
    );
    this.isLoading = false;
  }

  ngAfterViewInit() {
    this.dataSource.sort = this.sort;
  }

  public getTaskByWorkflow(idWorkflow: number) {
    this._router.navigate(['/sam/GEPR/GETA/GETA', idWorkflow]);
    // let workflowFilt = this.dataSource.data.filter(
    //   (item) => item.ID_WORKFLOW == idWorkflow
    // );
    // if (workflowFilt.length > 0) {
    //   this._dialog.open(ViewTaskWorkflowComponent, {
    //     disableClose: true,
    //     width: '900px',
    //     maxWidth: '900px',
    //     data: {
    //       idWorkflow: idWorkflow,
    //       module: workflowFilt[0].MODULO_WORKFLOW,
    //     },
    //   });
    // }
  }

  public openGraphicWorkflow(idWorkflow: number) {
    this._dialog.open(ViewGraphicWorkflowComponent, {
      disableClose: true,
      width: '900px',
      maxWidth: '900px',
      data: {
        idWorkflow: idWorkflow,
      },
    });
  }

  public async viewWorkflowDetails(idWorkflow: number) {
    console.log('Llamando getWorkflowById para ID:', idWorkflow);
    const user: string = this.resourcesService.getUser();
    const line: number = this.resourcesService.getLineNumber();

    await lastValueFrom(
      this._processManagementService.getWorkflowById(
        idWorkflow.toString(),
        user,
        line
      )
    ).then(
      (responseData: ResponseDataWorkflow) => {
        if (!responseData.error) {
          console.log('Respuesta getWorkflowById:', responseData);
          this._dialog.open(WorkflowDetailsComponent, {
            disableClose: true,
            width: '500px',
            maxWidth: '500px',
            data: {
              workflowData: responseData.response,
            },
          });
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      },
      (httpErrorResponse) => {
        this.resourcesService.checkErrors(httpErrorResponse);
      }
    );
  }

  public goForm(element: GetWorkflows) {
    this._dialog
      .open(FormWorkflowComponent, {
        disableClose: true,
        width: '500px',
        maxWidth: '500px',
        data: {
          type: 'UPD',
          idWorkflow: element.ID_WORKFLOW,
        },
      })
      .afterClosed()
      .subscribe(async (result) => {
        if (result) {
          await this.getWorkflows();
        }
      });
  }

  public changeWorkflowStatus(element: GetWorkflows) {
    this._dialog
      .open(ChangeStatusWorkflowComponent, {
        disableClose: true,
        width: '400px',
        data: {
          currentStatus: element.ESTADO,
        },
      })
      .afterClosed()
      .subscribe(async (result) => {
        if (result) {
          await this._changeStatus(
            element.ID_WORKFLOW,
            result.newStatus,
            result.comentario
          );
        }
      });
  }

  private async _changeStatus(
    idWorkflow: number,
    newStatus: string,
    comentario: string
  ) {
    this.isLoading = true;
    const changeStatusRequest: ChangeWorkflowStatusRequest = {
      ID_WORKFLOW: idWorkflow,
      ESTADO: newStatus,
      COMENTARIO_CAMBIO: comentario,
      USUARIO: this.resourcesService.getUser(),
      NUMERO_LINEA: this.resourcesService.getLineNumber(),
    };

    await lastValueFrom(
      this._processManagementService.changeWorkflowStatus(changeStatusRequest)
    ).then(
      async (responseData: ResponseData) => {
        if (!responseData.error) {
          this.resourcesService.openSnackBar(this.interService.get('cambio_estado_exitoso'));
          await this.getWorkflows();
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      },
      async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse);
        if (response !== null && response.reload) {
          await this._changeStatus(idWorkflow, newStatus, comentario);
        }
      }
    );
    this.isLoading = false;
  }

  public viewWorkflowHistory(idWorkflow: number) {
    this._dialog.open(WorkflowHistoryComponent, {
      disableClose: true,
      width: '700px',
      data: { idWorkflow },
    });
  }

  public openRegisterWorkflow() {
    this._dialog
      .open(FormWorkflowComponent, {
        disableClose: true,
        width: '500px',
        maxWidth: '500px',
        data: {
          type: 'REG',
        },
      })
      .afterClosed()
      .subscribe(async (result) => {
        if (result) {
          await this.getWorkflows();
        }
      });
  }

  public async activateWorkflowFromDraft(element: GetWorkflows) {
    const user: string = this.resourcesService.getUser();
    const line: number = this.resourcesService.getLineNumber();

    await lastValueFrom(
      this._processManagementService.getTaskByWorkflow(
        element.ID_WORKFLOW.toString(),
        user,
        line
      )
    ).then(
      (responseData: ResponseDataGetTaskByWorkflow) => {
        if (!responseData.error) {
          if (responseData.response.length === 0) {
            this.resourcesService.openSnackBar(
              this.interService.get('no_puede_activar_workflow')
            );
          } else {
            this.changeWorkflowStatus(element);
          }
        } else {
          this.resourcesService.openSnackBar(
            this.interService.get('error_verificar_tareas').replace('{0}', responseData.msg)
          );
        }
      },
      (httpErrorResponse: HttpErrorResponse) => {
        this.resourcesService.checkErrors(httpErrorResponse);
      }
    );
  }
}
