import { Component, Input } from '@angular/core';
import { Hotel } from '../HotelItem/hotel';
import { AbstractControl, FormControl, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
import { NgFor, NgIf } from '@angular/common';
import { HttpClient } from '@angular/common/http';
import { Router, RouterLink } from '@angular/router';

@Component({
  selector: 'app-hotel-form',
  standalone: true,
  imports: [ReactiveFormsModule, NgIf, NgFor, RouterLink],
  templateUrl: './hotel-form.component.html',
  styleUrl: './hotel-form.component.css'
})
export class HotelFormComponent {
  @Input() public hotel!: Hotel;
  public hotelForm!: FormGroup
  public errorMsg: string = 'testing';
  errorMessages: Record<string, string> = {};

  constructor(public http: HttpClient, public router: Router) {

  }

  private validationErrorMessages: Record<string, string> = {
    required: "This field is required",
    minlength: "The value is too short",
    maxlength: "The value is too long",
    pattern: "The value format is incorrect"
  };

  setMessage(value: AbstractControl): void {
    if ((value.touched || value.dirty) && value.errors) {
      this.errorMsg = Object.keys(value.errors).map(key => {
        console.log(this.validationErrorMessages[key]);
        return this.validationErrorMessages[key] || `Unknown error: ${key}`;
      }).join(' ');

    }
  }

  updateErrorMessages(): void {
    this.errorMessages = {};

    Object.keys(this.hotelForm.controls).forEach(field => {
      const control = this.hotelForm.get(field);

      if (control && control.errors) {
        this.errorMessages[field] = Object.keys(control.errors)
          .map(errorKey => this.validationErrorMessages[errorKey] || `Unknown error: ${errorKey}`)
          .join(' ');
      }
    });
  }

  ngOnInit(): void {
    this.hotelForm = new FormGroup({
      name: new FormControl(this.hotel.hotelName, Validators.required),
      description: new FormControl(this.hotel.description, Validators.required),
      price: new FormControl(this.hotel.price, Validators.required),
    });

    // this.hotelForm.valueChanges.subscribe(data => this.setMessage(this.hotelForm.get("name")!));
    // this.hotelForm.valueChanges.subscribe(data => this.setMessage(this.hotelForm.get("description")!));
    // this.hotelForm.valueChanges.subscribe(data => this.setMessage(this.hotelForm.get("price")!));
    //
    this.hotelForm.valueChanges.subscribe(() => this.updateErrorMessages());
  }

  submit(): void {
    this.hotel.hotelName = this.hotelForm.get("name")?.value;
    this.hotel.description = this.hotelForm.get("description")?.value;
    this.hotel.price = this.hotelForm.get("price")?.value;
    console.log(this.hotelForm.value);
    this.http.put("/api/hotels/" + this.hotel.id, this.hotel).subscribe();
    this.router.navigate(["/"]);
  }
}
