import { CommonModule } from '@angular/common';
import { Component, inject, Input, SimpleChanges } from '@angular/core';
import { ControlContainer, FormControl, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
import { SharedModule } from '../../../../shared/shared.module';

@Component({
  selector: 'app-radio-btn-input',
  standalone: true,
  imports: [ReactiveFormsModule, CommonModule, SharedModule],
  viewProviders:[
    {
      provide: ControlContainer,
      useFactory : ()=>inject(ControlContainer, { skipSelf : true })
    }
  ],
  template: `<input type="text" [ngClass]="classText" [id]="idField ? idField : nameField" [formControlName]="nameField" [value]="value" [placeholder]="placeholder">
  <div *ngIf="formControl.invalid && formControl.touched" class="error-invalid">
    <span class="text-danger" *ngIf="formControl.hasError('required')">{{'This field is required' | translate}}</span>
  </div>`
})
export class RadioBtnInputComponent {
  @Input() nameField!: string;
  @Input() value!: string;
  @Input() idField!: string;
  @Input() classText!: string;
  @Input() placeholder!: string;
  @Input() isRequired!: boolean;
  parentContainer = inject(ControlContainer);

  get parentFormGroup(){
    return this.parentContainer.control as FormGroup;
  }
  get formControl(): FormControl {
    return this.parentFormGroup.get(this.nameField) as FormControl;
  }

  ngOnInit() {
    this.parentFormGroup.addControl(this.nameField, new FormControl(this.value ?? '', this.isRequired ? Validators.required : null))
  }

  
  ngOnChanges(changes: SimpleChanges): void {
    // Check if the initialSelect input has changed
    if (changes['value']) {
      // Update the form control value
      this.updateFormControl();
    }
  }

  private updateFormControl(): void {
    if (this.parentFormGroup) {
      // Update the value of the form control
      const control = this.parentFormGroup.get(this.nameField);
      if (control) {
        control.setValue(this.value ?? '');
        control.setValidators(this.isRequired ? Validators.required : null);
        control.updateValueAndValidity();
      }
    }
  }
  ngOnDestroy() {
    this.parentFormGroup.removeControl(this.nameField);
  }
}
