import { Component, Inject } from '@angular/core';
import { ToastrService } from "ngx-toastr";
import { HttpClient } from "@angular/common/http";
import { MAT_DIALOG_DATA, MatDialogRef } from "@angular/material/dialog";
import { ConfigService } from '@services/config.service';

@Component({
  selector: 'app-create-calendar-rule',
  templateUrl: './create-calendar-rule.component.html',
  styleUrl: './create-calendar-rule.component.css'
})
export class CreateCalendarRuleComponent {
  baseUrl: string;
  name: string = '';
  remoteCalendarRules: any[] = [];
  weekDays: string[] = ['Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado', 'Domingo'];
  busyWeekDays: { [key: string]: boolean } = {};
  busyFromHour: any = null;
  busyToHour: any = null;
  availableFromDate: any = null;
  availableToDate: any = null;
  isRemoteAvailable: boolean = false;
  showAdditionalForm: boolean = false;
  availableReason: any = null;
  isEditMode: boolean = false;
  ruleId: string | null = null;
  calendarId: string | null = null;
  selectedDaysIndices: number[] = [];

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

  ngOnInit(): void {
    this.calendarId = this.data.calendar
    if (this.data) {
      this.isEditMode = true;
      this.availableFromDate = this.data.rule ? this.data.rule.availableFromDate : null;
      this.availableToDate = this.data.rule ? this.data.rule.availableToDate : null;
      this.isRemoteAvailable = this.data.rule ? this.data.rule.isRemoteAvailable : false;
      this.availableReason = this.data.rule ? this.data.rule.availableReason : null;
      this.busyFromHour = this.data.rule ? this.data.rule.busyFromHour : null;
      this.busyToHour = this.data.rule ? this.data.rule.busyToHour : null;
      if (this.data.rule && this.data.rule.busyWeekDays) {
        this.busyWeekDays = this.data.rule.busyWeekDays.reduce((acc: {
          [x: string]: boolean;
        }, day: string | number) => {
          // @ts-ignore
          acc[this.weekDays[day]] = true;
          return acc;
        }, {});
      }
      this.ruleId = this.data.rule ? this.data.rule['@id'] : null
    }
  }

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

  toggleAdditionalForm(): void {
    this.showAdditionalForm = !this.showAdditionalForm;
  }

  getSelectedDaysIndices() {
    this.selectedDaysIndices = this.weekDays
      .map((day, index) => this.busyWeekDays[day] ? index : -1)
      .filter(index => index !== -1);
  }

  submitRule(): void {
    this.getSelectedDaysIndices()
    const selectedDaysArray = Object.keys(this.busyWeekDays).map((day, index) => this.busyWeekDays[index]);

    const formData = {
      remoteCalendar: this.calendarId,
      busyWeekDays: this.selectedDaysIndices,
      busyFromHour: this.busyFromHour,
      busyToHour: this.busyToHour,
      availableFromDate: this.availableFromDate,
      availableToDate: this.availableToDate,
      isRemoteAvailable: this.isRemoteAvailable,
      availableReason: this.availableReason
    };

    if (this.isEditMode && this.ruleId) {
      this.http.put(`${this.baseUrl}${this.ruleId}`, formData)
        .subscribe({
          next: (response) => {
            this.toastService.success('Calendar updated successfully');
            this.dialogRef.close(true);
          },
          error: (error) => {
            console.error('Error:', error);
            this.toastService.error(error.error['hydra:description']);
          }
        });
    } else {
      this.http.post(`${this.baseUrl}/remote-calendar-rules`, formData)
        .subscribe({
          next: (response) => {
            this.toastService.success('Calendar created successfully');
            this.dialogRef.close(true);
          },
          error: (error) => {
            console.error('Error:', error);
            this.toastService.error(error.error['hydra:description']);
          }
        });
    }
    console.log(formData);
  }
}
