import { Injectable, ComponentFactoryResolver, ViewContainerRef } from '@angular/core';
import { TextFieldComponent } from './text-field.component';
import { NumberFieldComponent } from './number-field.component';
import { PhoneFieldComponent } from './phone-field.component';
import { ParagraphFieldComponent } from './paragraph-field.component';
import { PasswordFieldComponent } from './password-field.component';
import { TextareaFieldComponent } from './textarea-field.component';
import { BaseFieldComponent } from './base-field.component';

@Injectable({
  providedIn: 'root'
})
export class FieldFactoryService {
  private componentMap: any = {
    'text': TextFieldComponent,
    'number': NumberFieldComponent,
    'phone': PhoneFieldComponent,
    'paragraph': ParagraphFieldComponent,
    'password': PasswordFieldComponent,
    'textarea': TextareaFieldComponent
  };

  constructor(private componentFactoryResolver: ComponentFactoryResolver) {}

  createField(
    container: ViewContainerRef,
    fieldType: string,
    fieldConfig: any,
    value: any,
    valueChangeCallback: (value: any) => void
  ): any {
    const component = this.componentMap[fieldType];
    if (!component) {
      throw new Error(`Unsupported field type: ${fieldType}`);
    }

    const factory = this.componentFactoryResolver.resolveComponentFactory(component);
    const componentRef = container.createComponent(factory);
    
    // Cast to BaseFieldComponent to access properties safely
    const instance = componentRef.instance as BaseFieldComponent;
    (instance as any).field = fieldConfig;
    (instance as any).value = value;
    
    // Subscribe to value changes
    if ((instance as any).valueChange && typeof (instance as any).valueChange.subscribe === 'function') {
      (instance as any).valueChange.subscribe(valueChangeCallback);
    }
    
    return componentRef;
  }
}