import { Component, ChangeDetectionStrategy, OnInit, forwardRef, OnDestroy, ChangeDetectorRef, Input, HostBinding } from '@angular/core';
import { DateAdapter } from '@isa-ui/core/date';
import { Datepicker } from './datepicker';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-ui-datepicker',
  templateUrl: 'datepicker.component.html',
  styleUrls: ['datepicker.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  providers: [
    { provide: Datepicker, useExisting: forwardRef(() => UiDatepickerComponent) },
    { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => UiDatepickerComponent), multi: true },
  ],
  exportAs: 'uiDatepicker',
})
export class UiDatepickerComponent<TDate = any> extends Datepicker<TDate> implements ControlValueAccessor, OnInit, OnDestroy {
  @Input()
  @HostBinding('style.right')
  right: string;

  @Input()
  @HostBinding('style.left')
  left: string;

  opened = false;

  private subscription = new Subscription();

  onChange = (date: TDate) => {};

  onTouched = () => {};

  constructor(dateAdapter: DateAdapter<TDate>, private cdr: ChangeDetectorRef) {
    super(dateAdapter);
    const sub = this.selectedChange.subscribe((date) => {
      this.onChange(date);
      this.onTouched();
    });
    this.subscription.add(sub);
  }

  ngOnInit(): void {}

  ngOnDestroy() {
    this.subscription.unsubscribe();
    super.onDestroy();
  }

  writeValue(obj: TDate): void {
    this.setSelected(obj, { emit: false });
  }

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

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

  setDisabledState?(isDisabled: boolean): void {}

  open() {
    this.opened = true;
  }

  close() {
    this.opened = false;
  }

  toggle() {
    this.opened = !this.opened;
    this.cdr.markForCheck();
  }
}
