import { ChangeDetectionStrategy, ChangeDetectorRef, Component, computed, DoCheck, ElementRef, inject, Injector, input, model, OnInit, signal, ViewChild } from '@angular/core';
import { ControlValueAccessor, FormControl, FormControlDirective, FormControlName, FormGroupDirective, NG_VALUE_ACCESSOR, NgControl } from '@angular/forms';

type WrapType = 'hard' | 'soft';

@Component({
  selector: 'fast-textarea',
  imports: [],
  providers: [{
    provide: NG_VALUE_ACCESSOR,
    multi: true,
    useExisting: FastTextAreaComponent
  },
  {
    provide: NgControl,
    multi: true,
    useExisting: FastTextAreaComponent
  }],
  template: `
    <textarea #textAreaElement
      [class]="conditionalClasses()"
      [value]="value()"
      [maxLength]="maxLength()"
      [rows]="rows()"
      [autofocus]="autofocus()"
      (input)="onValueChange($event)"
      (blur)="onTouched()"
      [disabled]="isDisabled()"
      [readOnly]="readonly()"
    >
    <ng-content></ng-content>
</textarea>
    `,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class FastTextAreaComponent implements ControlValueAccessor, OnInit, DoCheck {
  @ViewChild("textAreaElement") public textAreaElement: ElementRef;

  cdr = inject(ChangeDetectorRef);
  injector = inject(Injector);

  readonly = input<boolean>(false);
  value = model<string | null>(null);
  disabled = input<boolean>(false);
  maxLength = input<number | null>(2000);
  rows = input<number>(4);
  autofocus = input<boolean>(false);
  wrap = input<WrapType>('soft');
  invalidTrigger = signal(0);
  formControl: FormControl;

  // Internal signal to track form control disabled state
  private formControlDisabled = signal<boolean>(false);

  // Computed signal that combines input disabled state and form control disabled state
  isDisabled = computed(() => this.disabled() || this.formControlDisabled());

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

  ngDoCheck() {
    //needed so that isInvalid is recomputed when the form control is touched with changing the value
    // and when `markAllAsTouched` is called on the parent form
    if (this.formControl?.touched)
      this.invalidTrigger.update((v) => v + 1);
  }

  ngOnInit() {
    const ngControl = this.injector.get(NgControl);

    if (ngControl instanceof FormControlName) {
      this.formControl = this.injector
        .get(FormGroupDirective)
        .getControl(ngControl)
    } else {
      this.formControl = (ngControl as FormControlDirective).form as FormControl;
    }
  }

  isInvalid = computed(() => {
    this.invalidTrigger();
    const control = this.formControl;
    if (control && !this.isDisabled() && !this.readonly())
      return control.invalid && (control.touched || control.dirty)
    else
      return false;
  });

  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;
  }

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

    this.value.set(newValue);
    this.onChange(newValue);
    this.invalidTrigger.update((v) => v + 1);
  }

  setDisabledState(isDisabled: boolean) {
    this.formControlDisabled.set(isDisabled);
    this.cdr.markForCheck();
  }

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

    classes.push(...this.getCommonClasses());
    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;
  }

  getCommonClasses() {
    return [
      "flex",
      "flex-col",
      "flex-grow",
      "h-full",
      "w-full",
      "items-stretch",
      "m-0",
      "px-3",
      "py-1.5",
      "border-1",
      "border-solid",
      "rounded-md",
      "overflow-auto",
      "focus:ring-4",
      "focus:outline-none",
    ];
  }

  getLightBaseClasses() {
    if (this.readonly() || this.disabled()) {
      return [
        "bg-transparent",
        "border-base-gray-500",
        "ring-base-blue-250/50",
        "text-base-black-1000"
      ];
    }
    else {
      const classes = [
        "bg-white",
        "border-base-gray-500",
        "ring-base-blue-250/50",
        "text-base-black-1000"
      ];

      if (this.isInvalid()) {
        classes.push(
          "border-red-500",
          "ring-red-500/50",
          "ring-2"
        );
      } else {
        classes.push(
          "border-base-gray-500",
          "ring-base-blue-250/50"
        );
      }

      return classes;
    }
  }

  getDarkBaseClasses() {
    if (this.readonly() || this.disabled()) {
      return [
        "bg-transparent",
        "dark:text-base-white-500",
        "dark:border-alt-blue-250",
        "dark:ring-base-blurple-250/50"
      ];
    }
    else {
      const classes = [
        "dark:bg-alt-gray-1000",
        "dark:text-base-white-500",
        "dark:border-alt-blue-250",
        "dark:ring-base-blurple-250/50"
      ];

      if (this.isInvalid()) {
        classes.push(
          "dark:border-red-500",
          "dark:ring-red-500/50"
        );
      } else {
        classes.push(
          "dark:border-alt-blue-250",
          "dark:ring-base-blurple-250/50"
        );
      }

      return classes;
    }
  }
}
