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

@Component({
  selector: 'app-create-subnet',
  templateUrl: './create-subnet.component.html',
  styleUrls: ['./create-subnet.component.css']
})
export class CreateSubnetComponent implements OnInit {
  baseUrl: string;
  subnetForm: FormGroup;
  isEditMode: boolean = false;
  subnetId: string | null = null;

  constructor(
    private toastService: ToastrService,
    private http: HttpClient,
    private fb: FormBuilder,
    private configService: ConfigService,
    public dialogRef: MatDialogRef<CreateSubnetComponent>,
    public dialog: MatDialog,
    @Inject(MAT_DIALOG_DATA) public data: any
  ) {
    this.baseUrl = this.configService.apiUrl;
    this.subnetForm = this.fb.group({
      name: ['', Validators.required],
      netmask: ['', Validators.required],
      ipAddress: ['', Validators.required],
      router: [''],
      dns: ['', Validators.pattern(/^(((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?),)*((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/)],
      nextServer: [''],
      bootFileName: ['']
    });
  }

  ngOnInit(): void {
    if (this.data) {
      this.loadData();
      this.isEditMode = true;
    }
  }

  loadData() {
    this.subnetId = this.data.uuid;
    this.subnetForm.patchValue({
      name: this.data.name,
      netmask: this.data.netmask,
      dns: this.data.dns,
      ipAddress: this.data.ipAddress,
      nextServer: this.data.nextServer,
      bootFileName: this.data.bootFileName,
      router: this.data.router
    });
  }

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

  save(): void {
    if (this.subnetForm.invalid) {
      this.toastService.error('Por favor, revisa los campos del formulario');
      return;
    }

    const payload = this.subnetForm.value;

    if (!this.isEditMode) {
      this.http.post(`${this.baseUrl}/subnets`, payload).subscribe({
        next: () => {
          this.toastService.success('Configuración de red añadida exitosamente');
          this.dialogRef.close();
        },
        error: (error) => {
          this.toastService.error(error.error['hydra:description']);
        }
      });
    } else {
      this.http.patch(`${this.baseUrl}/subnets/${this.subnetId}`, payload).subscribe({
        next: () => {
          this.toastService.success('Configuración de red actualizada exitosamente');
          this.dialogRef.close();
        },
        error: (error) => {
          this.toastService.error(error.error['hydra:description']);
        }
      });
    }
  }
}
