import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import {
  GetTask,
  GetTaskByWorkflow,
  ResponseDataGetTaskByWorkflow,
  ResponseDataWorkflow,
} 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 { SocketService } from '../../../services/socket.service';
import { lastValueFrom } from 'rxjs';
import { HttpErrorResponse } from '@angular/common/http';
import { FormTaskComponent } from './form-task/form-task.component';
import { AlertComponent } from '../../resources/dialogs/alert/alert.component';
import { TaskDetailsComponent } from './task-details/task-details.component';
import { RequestUserNumberLine } from '../../../interfaces/response-data';
import { ActivatedRoute } from '@angular/router';

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

  public dataSource: MatTableDataSource<GetTaskByWorkflow>;
  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 _socketService: SocketService,
    private _route: ActivatedRoute
  ) {
    this.isLoading = false;
    this.isLoadingForm = false;
    this.dataSource = new MatTableDataSource<GetTaskByWorkflow>();
    this.displayedColumns = [
      'SECUENCIA_NUM',
      'NOMBRE_TAREA',
      'DESCRIPCION',
      'SECUENCIA',
      'REQUIERE_VALIDACION',
      'REGLA_VALIDACION',
      'ESTADO',
      'ACCIONES',
    ];
  }

  async ngOnInit() {
    await this.getWorkflowStatus();
    await this.getTasks();

    this._socketService.currentConnections().subscribe((res) => {});
  }

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

  public async getTasks() {
    this.isLoading = true;
    const user: string = this.resourcesService.getUser();
    const line: number = this.resourcesService.getLineNumber();
    const idWorkflow = this._route.snapshot.paramMap.get('idworkflow') || '1';
    await lastValueFrom(
      this._processManagementService.getTaskByWorkflow(idWorkflow, user, line)
    ).then(
      (responseData: ResponseDataGetTaskByWorkflow) => {
        if (!responseData.error) {
          console.log(responseData);

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

  public goForm(typeForm: 'REG' | 'UPD', element?: GetTaskByWorkflow) {
    this._socketService.getConnections();
    const idWorkflow = this._route.snapshot.paramMap.get('idworkflow') || '1';

    if (typeForm === 'REG') {
      this._dialog
        .open(FormTaskComponent, {
          disableClose: true,
          width: '600px',
          maxWidth: '600px',
          data: {
            type: typeForm,
            idWorkflow: idWorkflow,
          },
        })
        .afterClosed()
        .subscribe(async (result) => {
          if (result) {
            await this.getTasks();
          }
        });
    } else if (typeForm === 'UPD' && element !== undefined) {
      this._dialog
        .open(FormTaskComponent, {
          disableClose: true,
          width: '600px',
          maxWidth: '600px',
          data: {
            type: typeForm,
            idTask: element.ID_TAREA,
            idWorkflow: idWorkflow,
          },
        })
        .afterClosed()
        .subscribe(async (result) => {
          if (result) {
            await this.getTasks();
          }
        });
    }
  }

  public alert(element: GetTaskByWorkflow) {
    this._dialog
      .open(AlertComponent, {
        disableClose: true,
        data: {
          title: this.interService.get('confirmar'),
          description: this.interService.get('esta_seguro_eliminar_tarea'),
          icon: `warning`,
        },
      })
      .afterClosed()
      .subscribe(async (result) => {
        if (result) {
          await this._deleteTask(element.ID_TAREA.toString());
        }
      });
  }

  public async _deleteTask(idTask: string) {
    this.isLoading = true;
    const encTask: string = await this._encService.encrypt(idTask);
    const requestDeleteTask: RequestUserNumberLine =
      this.resourcesService.objectUserLine();
    await lastValueFrom(
      this._processManagementService.deleteTask(encTask, requestDeleteTask)
    ).then(
      async (responseData: ResponseData) => {
        if (!responseData.error) {
          this.resourcesService.openSnackBar(this.interService.get('eliminacion_exitosa'));
          await this.getTasks();
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      },
      async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse);
        if (response !== null && response.reload) {
          await this._deleteTask(idTask);
        }
      }
    );
    this.isLoading = false;
  }

  public async getWorkflowStatus() {
    const user: string = this.resourcesService.getUser();
    const line: number = this.resourcesService.getLineNumber();
    const idWorkflow = this._route.snapshot.paramMap.get('idworkflow') || '1';

    await lastValueFrom(
      this._processManagementService.getWorkflowById(idWorkflow, user, line)
    ).then(
      (responseData: ResponseDataWorkflow) => {
        if (!responseData.error) {
          this.workflowStatus = responseData.response.ESTADO;
          this.canAddTasks = this.workflowStatus === 'Borrador';
        }
      },
      (httpErrorResponse: HttpErrorResponse) => {
        this.resourcesService.checkErrors(httpErrorResponse);
      }
    );
  }

  getSequenceNumber(index: number): number {
    return index + 1;
  }

  editTask(task: GetTaskByWorkflow) {
    this.goForm('UPD', task);
  }

  viewTaskDetails(task: GetTaskByWorkflow) {
    this._dialog.open(TaskDetailsComponent, {
      disableClose: true,
      width: '500px',
      maxWidth: '500px',
      data: {
        idTask: task.ID_TAREA
      }
    });
  }
}
