import { Maybe } from '@/core';
import { jalaliToGregorian, nowJalali } from '@/utils';
import { CommonModule } from '@angular/common';
import {
  AfterViewInit,
  Component,
  ElementRef,
  EventEmitter,
  Input,
  OnDestroy,
  Output,
  ViewChild,
} from '@angular/core';
import { FormControl, ReactiveFormsModule } from '@angular/forms';
import dayjs from 'dayjs';
import flatpickr from 'flatpickr-wrap';
import { Persian } from 'flatpickr-wrap/dist/l10n/fa';
import { BaseOptions, DateOption } from 'flatpickr-wrap/dist/types/options';
import { InputTextModule } from 'primeng/inputtext';
import { UikitFieldComponent } from '../uikit-field.component';

@Component({
  selector: 'uikit-datepicker',
  standalone: true,
  imports: [CommonModule, ReactiveFormsModule, InputTextModule, UikitFieldComponent],
  templateUrl: './datepicker.component.html',
})
export class UikitFlatpickrJalaliComponent implements AfterViewInit, OnDestroy {
  @Input() control?: FormControl<Maybe<string>>;
  @Input() placeholder = 'انتخاب تاریخ';
  @Input() label = 'تاریخ';
  @Input() disabled = false;
  @Input() name: string = 'datepicker';
  @Input() options: Partial<BaseOptions> = {};
  @Input() showLabel: boolean = true;
  @Input() showErrors: boolean = true;
  @Input() hint?: string;
  @Input() minDate?: DateOption;
  @Input() maxDate?: DateOption;

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

  @ViewChild('wrapper', { static: true }) wrapperRef!: ElementRef<HTMLElement>;

  private fpInstance: any | null = null;

  ngAfterViewInit(): void {
    this.fpInstance = flatpickr(this.wrapperRef.nativeElement, {
      wrap: true,
      ...this.options,
      locale: Persian,
      disableMobile: true,
      clickOpens: !this.disabled,
      minDate: this.minDate,
      maxDate: this.maxDate,
      now: nowJalali(),
      altInputClass: 'flatpicker-field w-full',
      altInput: true,
      dateFormat: 'Y-m-d',
      altFormat: 'Y/m/d',

      onChange: (selectedDates: Date[], dateStr: string) => {
        console.log('dateStr', jalaliToGregorian(dateStr));

        this.valueChange.emit(dateStr);
        if (this.control) this.control.setValue(dayjs(dateStr).toISOString());
      },
    });
  }

  ngOnDestroy(): void {
    if (this.fpInstance?.destroy) {
      this.fpInstance.destroy();
      this.fpInstance = null;
    }
  }
}
