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

@Component({
  selector: 'app-create-image',
  templateUrl: './create-image.component.html',
  styleUrls: ['./create-image.component.css']
})
export class CreateImageComponent implements OnInit {
  baseUrl: string;
  imageForm: FormGroup<any>;
  imageId: string | null = null;
  softwareProfiles: any[] = [];
  repositories: any[] = [];
  loading: boolean = false;
  isEditMode: boolean = false;
  partitionInfo: { [key: string]: string } = {};
  showWarning: boolean = false;

  constructor(
    private fb: FormBuilder,
    private http: HttpClient,
    public dialogRef: MatDialogRef<CreateImageComponent>,
    private toastService: ToastrService,
    private configService: ConfigService,
    private dataService: DataService,
    @Inject(MAT_DIALOG_DATA) public data: any
  ) {
    this.baseUrl = this.configService.apiUrl;
    this.imageForm = this.fb.group({
      name: ['', Validators.required],
      description: [''],
      comments: [''],
      remotePc: [false],
      isGlobal: [false],
      softwareProfile: [''],
      imageRepositories: [[], Validators.required],
    });
  }

  ngOnInit() {
    this.loading = true;
    if (this.data) {
      this.isEditMode = true;
      this.load();
    } else {
      this.loading = false;
    }
    this.fetchSoftwareProfiles();
    this.fetchRepositories();
  }

  load(): void {
    this.dataService.getImage(this.data).subscribe({
      next: (response) => {
        this.imageForm.patchValue({
          name: response.name,
          description: response.description,
          comments: response.comments,
          remotePc: response.remotePc,
          isGlobal: response.isGlobal,
          softwareProfile: response.softwareProfile ? response.softwareProfile['@id'] : null,
          imageRepositories: response.imageRepositories ? response.imageRepositories.map((r: any) => r.imageRepository['@id']) : [],
        });
        this.imageId = response['@id'];
        this.partitionInfo = response.partitionInfo;
        this.loading = false;
      },
      error: (err) => {
        console.error('Error fetching remote calendar:', err);
        this.loading = false;
      }
    });
  }

  changeIsGlobal() {
    this.showWarning = this.imageForm.get('isGlobal')?.value;
  }

  fetchSoftwareProfiles() {
    const url = `${this.baseUrl}/software-profiles`;
    this.http.get(url).subscribe({
      next: (response: any) => {
        this.softwareProfiles = response['hydra:member'];
      },
      error: (error) => {
        this.toastService.error('Error al obtener los perfiles de software');
      }
    });
  }

  fetchRepositories() {
    const url = `${this.baseUrl}/image-repositories`;
    this.http.get(url).subscribe({
      next: (response: any) => {
        this.repositories = response['hydra:member'];
      },
      error: (error) => {
        this.toastService.error('Error al obtener los repositorios de imágenes');
      }
    });
  }

  saveImage(): void {
    const payload: any = {
      name: this.imageForm.value.name,
      description: this.imageForm.value.description,
      comments: this.imageForm.value.comments,
      remotePc: this.imageForm.value.remotePc,
      isGlobal: this.imageForm.value.isGlobal,
      imageRepositories: this.imageForm.value.imageRepositories,
      ...(this.imageForm.value.softwareProfile ? { softwareProfile: this.imageForm.value.softwareProfile } : {}),
    };

    if (this.imageId) {
      this.http.put(`${this.baseUrl}${this.imageId}`, payload).subscribe(
        (response) => {
          this.toastService.success('Imagen editada correctamente');
          this.dialogRef.close();
        },
        (error) => {
          this.toastService.error(error['error']['hydra:description']);
        }
      );
    } else {
      this.http.post(`${this.baseUrl}/images`, payload).subscribe(
        (response) => {
          this.toastService.success('Imagen añadida correctamente');
          this.dialogRef.close();
        },
        (error) => {
          this.toastService.error(error['error']['hydra:description']);
        }
      );
    }
  }

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