import {
  Component,
  ChangeDetectionStrategy,
  Input,
  Output,
  EventEmitter,
  ChangeDetectorRef,
  forwardRef,
  OnInit,
  ViewChildren,
  QueryList,
} from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { InputDTO, InputOptionsDTO, OptionDTO } from '@swagger/crm';
import { UiCheckboxComponent } from '@ui/checkbox';

@Component({
  selector: 'page-customer-type-selector',
  templateUrl: 'customer-type-selector.component.html',
  styleUrls: ['customer-type-selector.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => CustomerTypeSelectorComponent),
      multi: true,
    },
  ],
})
export class CustomerTypeSelectorComponent implements OnInit, ControlValueAccessor {
  @ViewChildren(UiCheckboxComponent, { read: UiCheckboxComponent })
  checkboxes: QueryList<UiCheckboxComponent>;

  @Input()
  value: InputOptionsDTO;

  @Output()
  valueChange = new EventEmitter<InputOptionsDTO>();

  @Input()
  disabled: boolean;

  private onChange = (value: InputOptionsDTO) => {};
  private onTouched = () => {};

  constructor(private cdr: ChangeDetectorRef) {}

  ngOnInit(): void {}

  writeValue(obj: any): void {
    this.value = obj;
    this.cdr.markForCheck();
  }

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

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

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

  setValue(value: InputOptionsDTO) {
    this.onChange(value);
    this.onTouched();
  }

  check(checked: boolean = false, option: OptionDTO) {
    this.value.values.forEach((o) => {
      if (o.value === option.value) {
        o.selected = checked;
      } else {
        o.selected = false;
      }
    });
    this.cdr.markForCheck();
    this.onChange(this.value);
    this.onTouched();
  }
}
