import { Component, OnInit, 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 { PageEvent } from "@angular/material/paginator";
import { CreateCalendarComponent } from "./create-calendar/create-calendar.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-calendar',
  templateUrl: './calendar.component.html',
  styleUrl: './calendar.component.css'
})
export class CalendarComponent implements OnInit {
  baseUrl: string;
  private apiUrl: string;
  images: { downloadUrl: string; name: string; uuid: string }[] = [];
  dataSource = new MatTableDataSource<any>();
  length: number = 0;
  itemsPerPage: number = 10;
  page: number = 1;
  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');
  syncUds: boolean = false;
  columns = [
    {
      columnDef: 'id',
      header: 'ID',
      cell: (remoteCalendar: any) => `${remoteCalendar.id}`,
    },
    {
      columnDef: 'name',
      header: 'Nombre',
      cell: (remoteCalendar: any) => `${remoteCalendar.name}`
    },
    {
      columnDef: 'rulesLength',
      header: 'Nº de reglas',
      cell: (remoteCalendar: any) => `${remoteCalendar.remoteCalendarRules.length}`
    },
    {
      columnDef: 'createdAt',
      header: 'Fecha de creación',
      cell: (remoteCalendar: any) => `${this.datePipe.transform(remoteCalendar.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 configService: ConfigService,
    private joyrideService: JoyrideService
  ) {
    this.baseUrl = this.configService.apiUrl;
    this.apiUrl = `${this.baseUrl}/remote-calendars`;
  }

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

  addCalendar(): void {
    const dialogRef = this.dialog.open(CreateCalendarComponent, {
      width: '400px'
    });

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

  search(): void {
    this.loading = true;
    this.dataService.getRemoteCalendars(this.filters).subscribe(
      data => {
        this.dataSource.data = data;
        this.loading = false;
      },
      error => {
        console.error('Error fetching calendars', error);
        this.loading = false;
      }
    );
  }

  sync(calendar: any): void {
    this.syncUds = true;
    this.http.post(`${this.apiUrl}/${calendar.uuid}/sync-uds`, {}).subscribe({
      next: () => {
        this.toastService.success('Calendarios sincronizados correctamente');
        this.search();
        this.syncUds = false;
      },
      error: (error) => {
        this.toastService.error(error.error['hydra:description']);
        this.syncUds = false;
      }
    });
  }

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

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

  deleteCalendar(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('Calendar deleted successfully');
          },
          error: () => {
            this.toastService.error('Error deleting calendar');
          }
        });
      }
    });
  }

  applyFilter() {
    this.loading = true;
    this.http.get<any>(`${this.apiUrl}?page=${this.page}&itemsPerPage=${this.itemsPerPage}`).subscribe({
      next: (response) => {
        this.dataSource.data = response['hydra:member'];
        this.length = response['hydra:totalItems'];
        this.loading = false;
      },
      error: () => {
        this.loading = false;
      }
    });
  }

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

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