import { Component, Input, OnChanges, SimpleChanges, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ActivatedRoute } from '@angular/router';
import { FormService } from './../../../services/FormService.service';

@Component({
  selector: 'app-dynamic-form-component',
  templateUrl: './dynamic-form-component.component.html',
  styleUrls: ['./dynamic-form-component.component.css']
})
export class DynamicFormComponentComponent implements OnInit, OnChanges {
  @Input() formId?: string | number;  // Opcional porque puede venir por ruta o input
  form!: FormGroup;
  configuration: any;
  selectedTabIndex = 0;
  constructor(
    private route: ActivatedRoute,
    private formService: FormService,
    private fb: FormBuilder
  ) {}

  ngOnInit() {
    // Solo si no hay formId por input, intento leer el parámetro ruta
    if (!this.formId) {
      this.route.paramMap.subscribe(params => {
        const id = params.get('id');
        if (id) {
          this.loadForm(+id);
        }
      });
    }
  }

  ngOnChanges(changes: SimpleChanges) {
    if (changes['formId'] && this.formId) {
      this.loadForm(this.formId);
    }
  }

  loadForm(id: string | number) {
    this.formService.getFormById(Number(id)).subscribe({
      next: (response) => {
        if (response.success) {
          this.configuration = response.form.configuration;
          this.buildForm();
        } else {
          console.error('Formulario no encontrado');
        }
      },
      error: (err) => {
        console.error('Error al cargar formulario:', err);
      }
    });
  }

  buildForm() {
    if (!this.configuration || !this.configuration.tabs) {
      console.error('Configuración inválida o vacía');
      return;
    }

    const group: any = {};

    this.configuration.tabs.forEach((tab: any) => {
      tab.elements.forEach((el: any) => {
        const controlName = el.element.name;
        const validators = el.element.required ? [Validators.required] : [];
        group[controlName] = this.fb.control('', validators);
      });
    });

    this.form = this.fb.group(group);
  }

  onSubmit() {
    if (this.form.valid) {
      console.log('Formulario enviado con datos:', this.form.value);
      // Aquí podrías llamar al servicio para enviar los datos
    } else {
      console.log('Formulario inválido');
      this.form.markAllAsTouched();
    }
  }
}
