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

@Component({
  selector: 'app-commands',
  templateUrl: './commands.component.html',
  styleUrls: ['./commands.component.css']
})
export class CommandsComponent implements OnInit {
  baseUrl: string;
  private apiUrl: string;
  dataSource = new MatTableDataSource<any>();
  filters: { [key: string]: string | boolean } = {};
  length: number = 0;
  itemsPerPage: number = 20;
  page: number = 0;
  pageSizeOptions: number[] = [10, 20, 40, 100];
  datePipe: DatePipe = new DatePipe('es-ES');
  loading: boolean = false;
  columns = [
    {
      columnDef: 'id',
      header: 'ID',
      cell: (command: any) => `${command.id}`,
    },
    {
      columnDef: 'name',
      header: 'Nombre',
      cell: (command: any) => `${command.name}`
    },
    {
      columnDef: 'readOnly',
      header: 'Solo Lectura',
      cell: (command: any) => `${command.readOnly}`
    },
    {
      columnDef: 'createdAt',
      header: 'Fecha de creación',
      cell: (command: any) => `${this.datePipe.transform(command.createdAt, 'dd/MM/yyyy hh:mm:ss')}`,
    }
  ];
  displayedColumns = [...this.columns.map(column => column.columnDef), 'actions'];

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

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

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

  viewDetails(event: MouseEvent, command: any): void {
    event.stopPropagation();
    this.dialog.open(CommandDetailComponent, {
      width: '800px',
      data: command,
    });
  }

  openCreateCommandModal(): void {
    this.dialog.open(CreateCommandComponent, {
      width: '600px',
    }).afterClosed().subscribe(() => this.search());
  }

  editCommand(event: MouseEvent, command: any): void {
    event.stopPropagation();
    this.dialog.open(CreateCommandComponent, {
      width: '600px',
      data: command['@id']
    }).afterClosed().subscribe(() => this.search());
  }

  deleteCommand(event: MouseEvent, command: any): void {
    event.stopPropagation();
    this.dialog.open(DeleteModalComponent, {
      width: '300px',
      data: { name: command.name },
    }).afterClosed().subscribe((result) => {
      if (result) {
        this.http.delete(`${this.apiUrl}/${command.uuid}`).subscribe({
          next: () => {
            this.toastService.success('Comando eliminado con éxito');
            this.search();
          },
          error: (error) => {
            console.error('Error al eliminar el comando:', error);
          }
        });
      }
    });
  }

  onPageChange(event: any): void {
    this.page = event.pageIndex;
    this.itemsPerPage = event.pageSize;
    this.length = event.length;
    this.search();
  }

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

}
