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';
import { isMobileDevice } from '../utils/util';

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()"
      [placeholder]="placeholder()"
      (input)="onValueChange($event)"
      (blur)="onTouched()"
      [disabled]="isDisabled()"
      [readOnly]="readonly()"
      (focus)="scrollToForMobile()"
    >
    <ng-content></ng-content>
</textarea>
    `,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class FastTextAreaComponent implements ControlValueAccessor, OnInit, DoCheck {
  @ViewChild("textAreaElement") textAreaElement: ElementRef<HTMLTextAreaElement>;

  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');
  placeholder = input<string>('');
  invalidTrigger = signal(0);
  resizable = input<boolean>(true);
  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);
  }

  focus() {
    this.textAreaElement.nativeElement.focus();
  }

  scrollTo() {
    this.textAreaElement.nativeElement.scrollIntoView();
  }

  scrollToForMobile() {
    if (isMobileDevice())
      setTimeout(() => {
        this.textAreaElement.nativeElement.scrollIntoView();
      }, 200);
  }

  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() {
    const commonClasses = []
    commonClasses.push(
      "flex",
      "flex-col",
      "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",
    );

    if (this.resizable() === false)
      commonClasses.push('resize-none')

    return commonClasses
  }

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