import { ChangeDetectionStrategy, ChangeDetectorRef, Component, computed, inject, model } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';

@Component({
  selector: 'fast-textbox',
  imports: [],
  providers: [{
    provide: NG_VALUE_ACCESSOR,
    multi: true,
    useExisting: FastTextboxComponent
  }],
  template: `
    <input #inputElement
      class="w-full relative items-stretch flex flex-row flex-nowrap h-7 m-0 px-3 py-1.5 border-1 border-solid rounded-md overflow-clip
      focus:ring-4
      focus:outline-none"
      [class]="conditionalClasses()"
      [value]="value()"
      (input)="onValueChange($event)"
      (blur)="onTouched()"
      [disabled]="disabled()"
    />
    <ng-content></ng-content>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class FastTextboxComponent implements ControlValueAccessor {
  cdr = inject(ChangeDetectorRef);

  value = model<string | null>(null);
  disabled = model<boolean>(false);

  onChange: (value: string | null) => void;
  onTouched: () => void;

  writeValue(value: string | null) {
    this.value.set(value);
    this.cdr.markForCheck();
  }

  registerOnChange(fn: (value: string | null) => void) {
    this.onChange = fn;
  }

  registerOnTouched(fn: () => void) {
    this.onTouched = fn;
  }

  setDisabledState(isDisabled: boolean) {
    this.disabled.set(isDisabled);
  }

  onValueChange(event: Event) {
    const target = event.target as HTMLInputElement;
    const newValue = target.value;

    this.value.set(newValue);
    this.onChange(newValue);
  }

  conditionalClasses = computed(() => {
    const classes = [] as string[];

    classes.push(...this.getLightBaseClasses());
    classes.push(...this.getDarkBaseClasses());

    const conditionalClasses = this.getConditionalClassesFromArrays(classes);
    return conditionalClasses;
  });

  getConditionalClassesFromArrays(classArray: string[]): { [key: string]: boolean } {
    const classes: { [key: string]: boolean } = {};
    classArray.forEach(className => {
      classes[className] = true;
    });
    return classes;
  }

  getLightBaseClasses() {
    return [
      "bg-white",
      "border-base-gray-500",
      "ring-base-blue-250/50",
      "text-base-black-1000"
    ];
  }

  getDarkBaseClasses() {
    return [
      "dark:bg-alt-gray-1000",
      "dark:text-base-white-500",
      "dark:border-alt-blue-250",
      "dark:ring-base-blurple-250/50"
    ];
  }
}
