import { Component, signal } from '@angular/core';
import { MatTableDataSource } from "@angular/material/table";
import { DatePipe } from "@angular/common";
import { MatDialog } from "@angular/material/dialog";
import { HttpClient } from "@angular/common/http";
import { DataService } from "./data.service";
import { ToastrService } from "ngx-toastr";
import { DeleteModalComponent } from "../../shared/delete_modal/delete-modal/delete-modal.component";
import { PageEvent } from "@angular/material/paginator";
import { CreateSoftwareComponent } from "./create-software/create-software.component";
import { JoyrideService } from 'ngx-joyride';
import { ConfigService } from '@services/config.service';

@Component({
  selector: 'app-software',
  templateUrl: './software.component.html',
  styleUrl: './software.component.css'
})
export class SoftwareComponent {
  baseUrl: string;
  private apiUrl: string;
  images: { downloadUrl: string; name: string; uuid: string }[] = [];
  dataSource = new MatTableDataSource<any>();
  length: number = 0;
  itemsPerPage: number = 10;
  page: number = 0;
  pageSizeOptions: number[] = [5, 10, 20, 40, 100];
  loading: boolean = false;
  filters: { [key: string]: string } = {};
  alertMessage: string | null = null;
  readonly panelOpenState = signal(false);
  datePipe: DatePipe = new DatePipe('es-ES');
  columns = [
    {
      columnDef: 'id',
      header: 'ID',
      cell: (software: any) => `${software.id}`,
    },
    {
      columnDef: 'name',
      header: 'Nombre',
      cell: (software: any) => `${software.name}`
    },
    {
      columnDef: 'description',
      header: 'Descripción',
      cell: (software: any) => `${software.description}`
    },
    {
      columnDef: 'type',
      header: 'Tipo',
      cell: (software: any) => `${software.type}`
    },
    {
      columnDef: 'createdAt',
      header: 'Fecha de creación',
      cell: (software: any) => `${this.datePipe.transform(software.createdAt, 'dd/MM/yyyy hh:mm:ss')}`,
    }
  ];
  displayedColumns = [...this.columns.map(column => column.columnDef), 'actions'];

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

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

  addSoftware(): void {
    const dialogRef = this.dialog.open(CreateSoftwareComponent, {
      width: '600px'
    });

    dialogRef.afterClosed().subscribe(result => {
      this.search();
    });
  }

  search(): void {
    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'];
      },
      (error) => {
        console.error('Error fetching commands', error);
      }
    );
  }

  editSoftware(calendar: any): void {
    const dialogRef = this.dialog.open(CreateSoftwareComponent, {
      width: '600px',
      data: calendar['@id']
    });

    dialogRef.afterClosed().subscribe(result => {
      this.search();
    });
  }

  deleteSoftware(calendar: any): void {
    const dialogRef = this.dialog.open(DeleteModalComponent, {
      width: '400px',
      data: { name: calendar.name }
    });

    dialogRef.afterClosed().subscribe(result => {
      if (result) {
        const apiUrl = `${this.baseUrl}${calendar['@id']}`;

        this.http.delete(apiUrl).subscribe({
          next: () => {
            this.search();
            this.toastService.success('Software deleted successfully');
          },
          error: (error) => {
            this.toastService.error('Error deleting calendar');
          }
        });
      } else {
        console.log('calendar deletion cancelled');
      }
    });
  }

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

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

}
