import { Component, Inject, OnInit } from '@angular/core';
import { ToastrService } from "ngx-toastr";
import { HttpClient } from "@angular/common/http";
import { MAT_DIALOG_DATA, MatDialog, MatDialogRef } from "@angular/material/dialog";
import { CreateCalendarRuleComponent } from "../create-calendar-rule/create-calendar-rule.component";
import { DataService } from "../data.service";
import { DeleteModalComponent } from "../../../shared/delete_modal/delete-modal/delete-modal.component";
import { ConfigService } from '@services/config.service';

@Component({
  selector: 'app-create-calendar',
  templateUrl: './create-calendar.component.html',
  styleUrl: './create-calendar.component.css'
})
export class CreateCalendarComponent implements OnInit {
  baseUrl: string;
  name: string = '';
  remoteCalendarRules: any[] = [];
  isEditMode: boolean = false;
  calendarId: string | null = null;
  busyWeekDaysMap: string[] = [];

  constructor(
    private toastService: ToastrService,
    private http: HttpClient,
    private configService: ConfigService,
    public dialogRef: MatDialogRef<CreateCalendarComponent>,
    @Inject(MAT_DIALOG_DATA) public data: any,
    public dialog: MatDialog,
    private dataService: DataService,
  ) {
    this.baseUrl = this.configService.apiUrl;
  }

  ngOnInit(): void {
    if (this.data) {
      this.load()
    }
  }

  load(): void {
    this.dataService.getRemoteCalendar(this.data).subscribe({
      next: (response) => {
        this.isEditMode = true;
        this.name = response.name;
        this.remoteCalendarRules = response.remoteCalendarRules;
        this.calendarId = this.data;
        this.remoteCalendarRules.forEach(rule => {
          rule.busyWeekDaysMap = this.getBusyWeekDaysMap(rule.busyWeekDays);
        });
      },
      error: (err) => {
        console.error('Error fetching remote calendar:', err);
      }
    });
  }

  getBusyWeekDaysMap(indices: number[]): string[] {
    console.log(indices)
    const weekDays = ['Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado', 'Domingo'];
    return indices.map(index => weekDays[index]);
  }


  onNoClick(): void {
    this.dialogRef.close();
  }

  submitForm(): void {
    const payload = {
      name: this.name
    };

    if (this.isEditMode && this.calendarId) {
      this.http.patch(`${this.baseUrl}${this.calendarId}`, payload)
        .subscribe({
          next: (response) => {
            this.toastService.success('Calendar updated successfully');
            this.dialogRef.close(true);
            this.load()
          },
          error: (error) => {
            console.error('Error:', error);
            this.toastService.error(error.error['hydra:description']);
          }
        });
    } else {
      this.http.post(`${this.baseUrl}/remote-calendars`, payload)
        .subscribe({
          next: (response) => {
            this.toastService.success('Calendar created successfully');
            this.dialogRef.close(true);
            this.load()
          },
          error: (error) => {
            console.error('Error:', error);
            this.toastService.error(error.error['hydra:description']);
          }
        });
    }
  }

  createRule(rule: any = null): void {
    const dialogRef = this.dialog.open(CreateCalendarRuleComponent, {
      width: '700px',
      data: {
        calendar: this.calendarId,
        rule: rule
      },
    });

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

  deleteCalendarRule(rule: any): void {
    const dialogRef = this.dialog.open(DeleteModalComponent, {
      width: '400px',
    });

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

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