import { ChangeDetectionStrategy, ChangeDetectorRef, Component, forwardRef, HostBinding, HostListener, Input } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';

@Component({
  selector: 'ui-checkbox',
  templateUrl: 'checkbox.component.html',
  styleUrls: ['checkbox.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => UiCheckboxComponent),
      multi: true,
    },
  ],
})
export class UiCheckboxComponent implements ControlValueAccessor {
  private selected: any;
  @Input() value: any = true;
  @Input() showCheckbox = true;

  @HostBinding('class.disabled') @Input() disabled: boolean;
  @HostBinding('class.checked') get checked(): boolean {
    return this.selected == this.value;
  }

  get icon() {
    if (this.showCheckbox) {
      if (this.design === 'default') {
        return this.checked ? 'checkbox_checked' : 'checkbox';
      }
      if (this.design === 'filled') {
        return this.checked ? 'checked' : 'checkbox';
      }
    }
  }

  @Input()
  design: 'default' | 'filled' = 'default';

  @HostBinding('class')
  get styleClass() {
    return `style-${this.design}`;
  }

  private onChange = (v: any) => {};
  private onChangeForParent = (checked: boolean, value: any) => {};
  private onTouched = () => {};

  constructor(private cdr: ChangeDetectorRef) {}

  writeValue(obj: any): void {
    this.selectValue(obj, false);
  }

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

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

  registerOnChangeForParent(fn: (checked: boolean, value: any) => void) {
    this.onChangeForParent = fn;
  }

  setDisabledState?(isDisabled: boolean): void {
    this.disabled = isDisabled;
    this.cdr.markForCheck();
  }

  selectValue(value: any, emitEvent = true) {
    this.selected = value;

    if (emitEvent) {
      this.onChange(this.value);
      this.onChangeForParent(this.checked, this.value);
      this.onTouched();
    }

    this.cdr.markForCheck();
  }

  @HostListener('click')
  select() {
    if (this.disabled) {
      return;
    }
    if (this.checked) {
      this.selected = undefined;
    } else {
      this.selected = this.value;
    }

    this.onChange(this.checked ? this.value : undefined);
    this.onChangeForParent(this.checked, this.value);

    this.onTouched();
    this.cdr.markForCheck();
  }
}
