import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { MatDialog } from '@angular/material/dialog';
import { ToastrService } from 'ngx-toastr';
import { CreateTaskComponent } from './create-task/create-task.component';
import { DetailTaskComponent } from './detail-task/detail-task.component';
import { DeleteModalComponent } from '../../../shared/delete_modal/delete-modal/delete-modal.component';
import { JoyrideService } from 'ngx-joyride';
import { ConfigService } from '@services/config.service';

@Component({
  selector: 'app-commands-task',
  templateUrl: './commands-task.component.html',
  styleUrls: ['./commands-task.component.css']
})
export class CommandsTaskComponent implements OnInit {
  baseUrl: string;
  tasks: any[] = [];
  filters: { [key: string]: string | boolean } = {};
  length: number = 0;
  itemsPerPage: number = 10;
  page: number = 1;
  pageSizeOptions: number[] = [5, 10, 20, 40, 100];
  displayedColumns: string[] = ['taskid', 'notes', 'name', 'scheduledDate', 'enabled', 'actions'];
  loading: boolean = false;
  private apiUrl: string;

  constructor(private http: HttpClient, private dialog: MatDialog, private toastService: ToastrService,
    private configService: ConfigService,
    private joyrideService: JoyrideService) {
    this.baseUrl = this.configService.apiUrl;
    this.apiUrl = `${this.baseUrl}/command-tasks`;
  }

  ngOnInit(): void {
    this.loadTasks();
  }

  search(): void {
    this.page = 1;
    this.loadTasks();
  }

  loadTasks(): void {
    this.loading = true;
    this.http.get<any>(`${this.apiUrl}?page=${this.page}&itemsPerPage=${this.itemsPerPage}`, { params: this.filters }).subscribe(
      (data) => {
        this.tasks = data['hydra:member'];
        this.length = data['hydra:totalItems'];
        this.loading = false;
      },
      (error) => {
        console.error('Error fetching tasks', error);
        this.loading = false;
      }
    );
  }

  viewTaskDetails(task: any): void {
    this.dialog.open(DetailTaskComponent, {
      width: '800px',
      data: { task },
    }).afterClosed().subscribe(() => this.loadTasks());
  }

  openCreateTaskModal(): void {
    this.dialog.open(CreateTaskComponent, {
      width: '800px',
    }).afterClosed().subscribe(() => this.loadTasks());
  }

  editTask(task: any): void {
    this.dialog.open(CreateTaskComponent, {
      width: '800px',
      data: { task },
    }).afterClosed().subscribe(() => this.loadTasks());
  }

  deleteTask(task: any): void {
    this.dialog.open(DeleteModalComponent, {
      width: '300px',
      data: { name: task.createdBy },
    }).afterClosed().subscribe((result) => {
      if (result) {
        this.http.delete(`${this.apiUrl}/${task.uuid}`).subscribe({
          next: () => {
            this.toastService.success('Tarea eliminada con éxito');
            this.loadTasks();
          },
          error: (error) => {
            console.error('Error al eliminar la tarea:', error);
          }
        });
      }
    });
  }

  onPageChange(event: any): void {
    this.page = event.pageIndex + 1;
    this.itemsPerPage = event.pageSize;
    this.loadTasks();
  }

  iniciarTour(): void {
    this.joyrideService.startTour({
      steps: [
        'titleStep',
        'addTaskStep',
        'searchStep',
        'tableStep',
        'actionsStep',
        'paginationStep'
      ],
      showPrevButton: true,
      themeColor: '#3f51b5'
    });
  }

}
