import { Component, OnInit } 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 { ToastrService } from "ngx-toastr";
import { JoyrideService } from "ngx-joyride";
import { Router } from "@angular/router";
import { DeleteModalComponent } from "../../shared/delete_modal/delete-modal/delete-modal.component";
import { CreateMenuComponent } from "./create-menu/create-menu.component";
import { ConfigService } from '@services/config.service';

@Component({
  selector: 'app-menus',
  templateUrl: './menus.component.html',
  styleUrl: './menus.component.css'
})
export class MenusComponent implements OnInit {
  baseUrl: string;
  private apiUrl: string;
  dataSource = new MatTableDataSource<any>();
  length: number = 0;
  itemsPerPage: number = 10;
  page: number = 0;
  loading: boolean = false;
  filters: { [key: string]: string } = {};
  datePipe: DatePipe = new DatePipe('es-ES');
  columns = [
    {
      columnDef: 'id',
      header: 'Id',
      cell: (menu: any) => `${menu.id}`
    },
    {
      columnDef: 'name',
      header: 'Nombre de menú',
      cell: (menu: any) => `${menu.name}`
    },
    {
      columnDef: 'publicUrl',
      header: 'Url pública',
      cell: (menu: any) => `${this.baseUrl}/menu/${menu.publicUrl}`
    },
    {
      columnDef: 'isDefault',
      header: 'Por defecto',
      cell: (menu: any) => `${menu.isDefault}`
    },
    {
      columnDef: 'resolution',
      header: 'Resolución',
      cell: (menu: any) => `${menu.resolution}`
    },
    {
      columnDef: 'createdAt',
      header: 'Fecha de creación',
      cell: (menu: any) => `${this.datePipe.transform(menu.createdAt, 'dd/MM/yyyy hh:mm:ss')}`
    }
  ];
  displayedColumns = [...this.columns.map(column => column.columnDef), 'actions'];

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

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

  addMenu(): void {
    const dialogRef = this.dialog.open(CreateMenuComponent, {
      width: '1000px'
    });

    dialogRef.afterClosed().subscribe(() => {
      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 images', error);
        this.loading = false;
      }
    );
  }

  editMenu(event: MouseEvent, menu: any): void {
    event.stopPropagation();
    this.dialog.open(CreateMenuComponent, {
      width: '1200px',
      data: menu['@id']
    }).afterClosed().subscribe(() => this.search());
  }

  deleteMenu(event: MouseEvent, menu: any): void {
    event.stopPropagation();
    this.dialog.open(DeleteModalComponent, {
      width: '300px',
      data: { name: menu.name },
    }).afterClosed().subscribe((result) => {
      if (result) {
        this.http.delete(`${this.apiUrl}/${menu.uuid}`).subscribe({
          next: () => {
            this.toastService.success('Menu eliminado con éxito');
            this.search();
          },
          error: (error) => {
            console.error('Error al eliminar el menú:', 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',
        'addStep',
      ],
      showPrevButton: true,
      themeColor: '#3f51b5'
    });
  }
}
