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 { PreventableEvent } from '@progress/kendo-angular-dropdowns';

export type MultiValueType<T> = T[] | string[] | number[] | null;

@Component({
  selector: 'fast-multiselect',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [FAST_KENDO_COMMON],
  providers: [{
    provide: NG_VALUE_ACCESSOR,
    multi: true,
    useExisting: FastMultiselectComponent
  },
  {
    provide: NgControl,
    multi: true,
    useExisting: FastMultiselectComponent
  }],
  template: `
  <kendo-multiselect
    [data]="data()"
    [textField]="textField()"
    [valueField]="valueField()"
    [valuePrimitive]="valuePrimitive()"
    [filterable]="true"
    [value]="value()"
    [size]="'small'"
    [placeholder]="placeholder()"
    (filterChange)="onFilterChange($event)"
    (valueChange)="onValueChange($event)"
    [class]="conditionalClasses()"
    [disabled]="isDisabled()"
    (open)="preventOpenBox($event)"
  />
  `
})
export class FastMultiselectComponent<T extends object> implements ControlValueAccessor, OnInit, DoCheck {
  cdr = inject(ChangeDetectorRef);
  injector = inject(Injector);

  data = input.required<MultiValueType<T>>();
  textField = input<string>(null);
  valueField = input<string>(null);
  valuePrimitive = input<boolean>(true);
  placeholder = input<string>('');
  disabled = input<boolean>(false);
  filterChange = output<string>();
  valueChange = output<MultiValueType<T>>();
  value = model<MultiValueType<T>>(null);
  preventOpen = input<boolean>(false);
  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: MultiValueType<T>) => void = () => { };
  onTouched = () => { };

  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: MultiValueType<T>) {
    this.value.set(value);
    this.cdr.markForCheck();
  }

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

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

  //onValueChange must take MultiValueType parameter
  // use util isObjectArray,isNumberArray,isStringArray to check sub-type
  onValueChange(newValue: MultiValueType<T>) {
    this.value.set(newValue);
    this.onChange(newValue);
    this.invalidTrigger.update((v) => v + 1);
  }

  onFilterChange(event: string): void {
    this.filterChange.emit(event);
  }

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

  preventOpenBox(event: PreventableEvent) {
    if (this.preventOpen())
      event.preventDefault();
  }

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

    classes.push(...this.getCommonClasses());
    classes.push(...this.getLightBaseClasses());
    classes.push(...this.getDarkBaseClasses());
    if (!this.isDisabled()) {
      classes.push(...this.getLightHoverClasses());
      classes.push(...this.getDarkHoverClasses());
    }

    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 [
      "items-center",
      "h-full",
      "overflow-visible",
      "[&_.k-input-inner]:m-0",
      "[&_.k-input-inner]:pl-2",
      "[&_.k-input-inner]:p-px",
      "[&_.k-input-values]:gap-0.5",
      "[&_.k-chip-list_.k-chip]:leading-normal",
      "[&_.k-chip-list_.k-chip]:mt-0.5",
      "[&_.k-chip-list_.k-chip]:mb-0",
      "[&_.k-chip-list_.k-chip]:p-0",
      "[&_.k-chip-list_.k-chip]:bg-transparent",
      "[&_.k-chip-list_.k-chip-content]:leading-4",
      "[&_.k-chip-list_.k-chip-content]:m-0",
      "[&_.k-chip-list_.k-chip-content]:p-0",
      "[&_.k-chip-list_.k-chip.k-chip-solid-base]:bg-transparent",
      "[&_.k-chip-label]:px-0.5",
      "[&_.k-chip-label]:py-2"
    ];
  }

  getLightBaseClasses() {
    const classes = [
      "[&_.k-chip-list_.k-chip.k-chip-solid-base]:border-base-gray-500",
      "[&_.k-chip-list_.k-chip]:text-base-black-1000",
      "[&_.k-chip-actions]:text-base-gray-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() {
    const classes = [
      "dark:[&_.k-chip-list_.k-chip.k-chip-solid-base]:border-base-gray-1000",
      "dark:[&_.k-chip-list_.k-chip]:text-base-white-500",
      "dark:[&_.k-chip-actions]:text-base-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;
  }

  getLightHoverClasses() {
    return [
      "[&_.k-chip-list_.k-chip]:hover:text-base-black-250",
      "[&_.k-chip-list_.k-chip.k-chip-solid-base]:hover:bg-base-gray-250",
      "[&_.k-chip-actions]:hover:text-base-red-1000",];
  }

  getDarkHoverClasses() {
    return [
      "dark:[&_.k-chip-list_.k-chip]:hover:text-base-white-1000",
      "dark:[&_.k-chip-list_.k-chip.k-chip-solid-base]:hover:bg-alt-blue-250",
      "dark:[&_.k-chip-actions]:hover:text-alt-red-500",];
  }
}
