import { Component, Input, Output, EventEmitter, ViewChild, ViewContainerRef, ComponentFactoryResolver } from '@angular/core';
import { FieldConfig } from '../field-types/base-field.component';
import { FieldFactoryService } from '../field-types/field-factory.service';

@Component({
  selector: 'app-dynamic-form',
  template: `
    <form [class]="formClass" (ngSubmit)="onSubmit()">
      <div class="clr-row">
        <div 
          *ngFor="let field of fields" 
          [class]="'clr-col-' + (field.colSpan || 12) + ' clr-col-sm-12'"
        >
          <ng-container #fieldContainer></ng-container>
        </div>
      </div>
      
      <div class="sq-form-actions" *ngIf="showActions">
        <button 
          type="button" 
          class="sq-btn sq-btn-outline" 
          (click)="onCancel()"
          [disabled]="isSubmitting"
        >
          <clr-icon shape="times"></clr-icon>
          <span>{{ cancelText }}</span>
        </button>
        <button 
          type="submit" 
          class="sq-btn sq-btn-primary" 
          [disabled]="isSubmitting"
        >
          <clr-icon [attr.shape]="submitIcon"></clr-icon>
          <span>{{ submitText }}</span>
        </button>
      </div>
    </form>
  `
})
export class DynamicFormComponent {
  @Input() fields: FieldConfig[] = [];
  @Input() formData: any = {};
  @Input() formClass: string = 'sq-form';
  @Input() showActions: boolean = true;
  @Input() submitText: string = 'Submit';
  @Input() cancelText: string = 'Cancel';
  @Input() submitIcon: string = 'check';
  
  @Output() formSubmit = new EventEmitter<any>();
  @Output() formCancel = new EventEmitter<void>();
  
  @ViewChild('fieldContainer', { read: ViewContainerRef }) fieldContainer: ViewContainerRef;
  
  isSubmitting = false;
  
  constructor(
    private fieldFactory: FieldFactoryService,
    private componentFactoryResolver: ComponentFactoryResolver
  ) {}
  
  ngAfterViewInit() {
    this.renderFields();
  }
  
  renderFields() {
    this.fieldContainer.clear();
    
    this.fields.forEach(field => {
      this.fieldFactory.createField(
        this.fieldContainer,
        field.type,
        field,
        this.formData[field.name],
        (value) => {
          this.formData[field.name] = value;
        }
      );
    });
  }
  
  onSubmit() {
    this.isSubmitting = true;
    this.formSubmit.emit(this.formData);
  }
  
  onCancel() {
    this.formCancel.emit();
  }
}