import { Component, Inject, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from "@angular/forms";
import { HttpClient } from "@angular/common/http";
import { MAT_DIALOG_DATA, MatDialogRef } from "@angular/material/dialog";
import { ToastrService } from "ngx-toastr";
import { DataService } from "../data.service";
import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser';
import { ConfigService } from '@services/config.service';

@Component({
  selector: 'app-create-menu',
  templateUrl: './create-menu.component.html',
  styleUrl: './create-menu.component.css'
})
export class CreateMenuComponent implements OnInit {
  baseUrl: string;
  menuForm: FormGroup<any>;
  menuId: string | null = null;
  softwareProfiles: any[] = [];
  safeUrl: SafeResourceUrl | null = null;

  constructor(
    private fb: FormBuilder,
    private http: HttpClient,
    public dialogRef: MatDialogRef<CreateMenuComponent>,
    private toastService: ToastrService,
    private dataService: DataService,
    private configService: ConfigService,
    private sanitizer: DomSanitizer,
    @Inject(MAT_DIALOG_DATA) public data: any
  ) {
    this.baseUrl = this.configService.apiUrl;
    this.menuForm = this.fb.group({
      name: ['', Validators.required],
      publicUrl: ['', Validators.required],
      resolution: ['', Validators.required],
      isDefault: [false],
      comments: [''],
    });
  }

  updateSafeUrl(): void {
    const url = `${this.baseUrl}/menu/${this.menuForm.get('publicUrl')?.value}`;
    if (url) {
      this.safeUrl = this.sanitizer.bypassSecurityTrustResourceUrl(url);
    } else {
      this.safeUrl = null;
    }
  }

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

  load(): void {
    this.dataService.getMenu(this.data).subscribe({
      next: (response) => {
        this.menuForm = this.fb.group({
          name: [response.name, Validators.required],
          publicUrl: [response.publicUrl, Validators.required],
          resolution: [response.resolution, Validators.required],
          comments: [response.comments],
          isDefault: [response.isDefault],
        });
        this.menuId = response['@id'];
        this.updateSafeUrl()
      },
      error: (err) => {
        console.error('Error fetching remote calendar:', err);
      }
    });
  }

  save(): void {
    const payload = {
      name: this.menuForm.value.name,
      publicUrl: this.menuForm.value.publicUrl,
      resolution: this.menuForm.value.resolution,
      comments: this.menuForm.value.comments,
      isDefault: this.menuForm.value.isDefault,
    };

    if (this.menuId) {
      this.http.put(`${this.baseUrl}${this.menuId}`, payload).subscribe(
        (response) => {
          this.toastService.success('Menu editado correctamente');
          this.dialogRef.close();
        },
        (error) => {
          this.toastService.error(error['error']['hydra:description']);
          console.error('Error al editar la imagen', error);
        }
      );
    } else {
      this.http.post(`${this.baseUrl}/menus`, payload).subscribe(
        (response) => {
          this.toastService.success('Menu añadido correctamente');
          this.dialogRef.close();
        },
        (error) => {
          this.toastService.error(error['error']['hydra:description']);
          console.error('Error al añadir el menu', error);
        }
      );
    }
  }

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