import { ChangeDetectionStrategy, ChangeDetectorRef, Component, computed, DoCheck, inject, Injector, input, model, OnInit, output, signal } from '@angular/core';
import { FAST_KENDO_COMMON } from '../../app.config';
import { ControlValueAccessor, FormControl, FormControlDirective, FormControlName, FormGroupDirective, NG_VALUE_ACCESSOR, NgControl } from '@angular/forms';
import { NumberFormatOptions } from '@progress/kendo-angular-intl';

@Component({
  selector: 'fast-numerictextbox',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [FAST_KENDO_COMMON],
  providers: [{
    provide: NG_VALUE_ACCESSOR,
    multi: true,
    useExisting: FastNumericTextBoxComponent
  },
  {
    provide: NgControl,
    multi: true,
    useExisting: FastNumericTextBoxComponent
  }],
  template: `
  <kendo-numerictextbox
    [min]="min()"
    [max]="max()"
    [class]="conditionalClasses()"
    [autoCorrect]="autoCorrect()"
    [format]="format()"
    [spinners]="spinners()"
    [step]="step()"
    [tabindex]="tabindex()"
    [value]="value()"
    (valueChange)="onValueChange($event)"
    [disabled]="isDisabled()"
    [decimals]="decimals()"
  />
  `
})
export class FastNumericTextBoxComponent implements ControlValueAccessor, OnInit, DoCheck {
  cdr = inject(ChangeDetectorRef);
  injector = inject(Injector);

  min = input<number | null>(null);
  max = input<number | null>(null);
  tabindex = input<number>(0);
  spinners = input<boolean>(true);
  step = input<number>(1);
  autoCorrect = input<boolean>(false);
  disabled = input<boolean>(false);
  valueChange = output<number | null>();
  format = input<string | NumberFormatOptions>();
  value = model<number | null>(null);
  decimals = input<number>(0);
  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: number | 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())
      return control.invalid && (control.touched || control.dirty)
    else
      return false;
  });

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

  registerOnChange(fn: () => void) {
    this.onChange = fn;
  }

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

  onValueChange(newValue: number | null) {
    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());

    if (!this.disabled()) {
      classes.push(...this.getLightBaseClasses());
      classes.push(...this.getDarkBaseClasses());
      classes.push(...this.getLightActiveClasses());
      classes.push(...this.getDarkActiveClasses());
    }

    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",
      "border-solid",
      "rounded-sm",
      "h-7",
      "[&_button]:border-none",
      "[&_button]:w-5.5",
      "[&_input]:pr-0",];
  }

  getLightBaseClasses() {
    const classes = [
      "[&_button]:text-base-black-1000",
      "[&_button]:bg-base-white-250"];

    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() {
    const classes = [
      "dark:[&_button]:text-base-white-500",
      "dark:[&_button]:bg-alt-gray-1000"];

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

  getLightActiveClasses() {
    return [
      "[&_button]:active:bg-base-white-1000"];
  }

  getDarkActiveClasses() {
    return [
      "dark:[&_button]:active:bg-alt-blue-250"];
  }
}
