import { Component, ChangeDetectionStrategy, ChangeDetectorRef, ViewChild, ElementRef, HostListener, inject } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { tap, take, map, catchError, switchMap, filter, shareReplay, retry } from 'rxjs/operators';
import { of, BehaviorSubject, Subject, combineLatest } from 'rxjs';
import { State } from '@progress/kendo-data-query';
import { MessageService } from '../_shared/services/message.service';
import { Validators } from '@angular/forms';
import { CustomFormBuilder } from '../_shared/services/custom-form-builder.service';
import { DialogService, DialogSettings } from '@progress/kendo-angular-dialog';
import { NotifyService } from '../_shared/services/notify.service';
import { saveAs } from '@progress/kendo-file-saver';
import * as util from '../_shared/utils/util';
import { HolidayService, Item, Detail, SaveType, RequiredData } from './holiday.service';
import { FAST_KENDO_COMMON, FAST_PAGE_COMMON } from '../app.config';

@Component({
  selector: 'app-holiday',
  templateUrl: './holiday.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [FAST_PAGE_COMMON, FAST_KENDO_COMMON]
})
export class HolidayComponent {
  private service = inject(HolidayService);
  private messageService = inject(MessageService);
  private titleService = inject(Title);
  private fb = inject(CustomFormBuilder);
  private ref = inject(ChangeDetectorRef);
  private dialogService = inject(DialogService);
  private notify = inject(NotifyService);

  @ViewChild("grid", { read: ElementRef }) kendoGridEl: ElementRef;
  @HostListener('window:resize') onResize() {
    //this function is empty but for some reason it helps the window to resize faster
  };

  constructor() {

  }

  util = util;

  detailForm = this.getDetailForm();
  gridScrollPosition: util.GridScrollPosition = { topPos: 0, leftPos: 0 };
  localRequiredData: RequiredData;
  hasModifyPermission = false;
  detailInitialValues: Detail = this.detailForm.value as Detail;
  mySelection: number[] = [];

  gridLoading$ = new BehaviorSubject<boolean>(true)
  refreshItems$ = new BehaviorSubject<string>(null)
  exporting$ = new BehaviorSubject<boolean>(false)
  detailOpened$ = new BehaviorSubject<boolean>(false)
  refreshRequiredData$ = new BehaviorSubject(null)
  detailLoading$ = new BehaviorSubject<boolean>(true)
  refreshDetail$ = new BehaviorSubject<number>(null)
  save$ = new Subject<SaveType>()
  delete$ = new Subject()
  exportClicked$ = new Subject()

  state: State = {
    filter: null,
    group: null,
    skip: 0,
    sort: [{ field: 'Date', dir: 'asc' }],
    take: 50
  };

  getDetailForm() {
    const fb = this.fb;
    const fg: util.FormModel<Detail> = fb.group({
      holidayId: fb.ctr(0, Validators.required),
      holidayName: fb.ctr(null, Validators.required),
      holidayDate: fb.ctr(util.currentDate.toDate(), Validators.required),
      holidayScheduleId: fb.ctr(1, Validators.required)
    });

    return fg;
  }

  requiredData$ = this.refreshRequiredData$.pipe(
    tap(() => this.detailLoading$.next(true)),
    switchMap(refreshType => {
      return combineLatest([this.service.requiredData$, of(refreshType)]);
    }),
    map(([requiredData, refreshType]) => {
      this.localRequiredData = requiredData;
      if (refreshType === util.RefreshType.SelfOnly)
        this.detailLoading$.next(false);
      return requiredData;
    }),
    tap((requiredData) => {
      this.hasModifyPermission = requiredData.hasModifyPermission;
      util.focusInputTarget()
    }),
    shareReplay(1),
    catchError(err => {
      return util.handleError(err, this.messageService)
    }), retry(10)
  )

  items$ = this.refreshItems$.pipe(
    tap(() => {
      this.gridLoading$.next(true);
    }),
    switchMap(() => {
      return this.service.getItems(this.state);
    }),
    tap(() => {
      this.gridLoading$.next(false);
      util.goToSavedGridScrollPos(this.kendoGridEl, this.gridScrollPosition);
    }),
    shareReplay(1),
    catchError(err => {
      return util.handleError(err, this.messageService);
    }), retry(10)
  )

  exportAction$ = this.exportClicked$.pipe(
    tap(() => {
      this.exporting$.next(true);
    }),
    switchMap(() => {
      return this.service.exportItems(this.state, 'Holidays.xlsx');
    }),
    tap(res => {
      saveAs(res.fileBlob, res.fileName);
      this.exporting$.next(false);
    }),
    shareReplay(1),
    catchError(err => {
      this.exporting$.next(false);
      return util.handleError(err, this.messageService);
    }), retry(10)
  )

  detail$ = this.refreshDetail$.pipe(
    filter(id => id !== null),
    switchMap(id => {
      this.detailLoading$.next(true);
      this.detailForm.disable();
      this.detailForm.reset();
      if (id === 0)
        return of(this.detailInitialValues);
      else
        return this.service.getDetail(id);
    }),
    map(result => {
      const detail: Detail = result;
      if (detail) {
        util.convertToDates(detail);
        this.detailForm.setValue(detail);
      }
      return detail;
    }),
    tap(() => {
      this.detailFinishedLoading();
    }),
    shareReplay(1),
    catchError(err => {
      this.closeDetail(false);
      return util.handleError(err, this.messageService)
    }), retry(10)
  )

  saveResult$ = this.save$.pipe(
    switchMap(saveType => {
      this.detailLoading$.next(true);
      this.detailForm.disable();
      const itemToSave: Detail = this.detailForm.value as Detail;
      return this.service.saveDetail(itemToSave, saveType);
    }),
    tap(saveResult => {
      this.notify.success('save successful');
      this.closeDetail(false);
      this.refreshItems$.next(null);
      this.mySelection = [saveResult];
    }),
    shareReplay(1),
    catchError(err => {
      this.detailFinishedLoading();
      return util.handleError(err, this.messageService)
    }), retry(10)
  )

  deleteResult$ = this.delete$.pipe(
    switchMap(() => {
      this.detailLoading$.next(true);
      this.detailForm.disable();
      const itemToDelete: Detail = this.detailForm.getRawValue();
      return this.service.deleteDetail(itemToDelete.holidayId);
    }),
    tap(() => {
      this.notify.success('delete successful');
      this.detailFinishedLoading();
      this.closeDetail(false);
      this.refreshItems$.next(null);
    }),
    shareReplay(1),
    catchError(err => {
      return util.handleError(err, this.messageService)
    }), retry(10)
  )

  openDetail(id: number): void { //error hitting here
    util.saveGridScrollPos(this.kendoGridEl, this.gridScrollPosition);
    this.refreshDetail$.next(id);
    this.detailOpened$.next(true);
  }

  onDetailClosing() {
    util.onDetailChanging(this.detailForm, this.dialogService, this.closeDetail, this.save);
  }

  closeDetail = (isFromInterface: boolean) => {
    this.detailOpened$.next(false);

    if (isFromInterface)
      util.goToSavedGridScrollPos(this.kendoGridEl, this.gridScrollPosition);
  }

  detailFinishedLoading(): void {
    this.detailForm.enable();
    this.detailLoading$.next(false);
    util.focusInputTarget();
  }

  add(): void {
    this.openDetail(0);
  }

  edit(dataItem: Item): void {
    this.openDetail(dataItem.HolidayId);
  }

  save = (saveType: util.SaveType) => {
    this.detailForm.markAllAsTouched();
    if (this.detailForm.valid)
      this.save$.next(saveType);
    else
      this.notify.error("validation failed");
  }

  delete(): void {
    const deleteConfirmSettings: DialogSettings = {
      title: "Please confirm",
      content: "Are you sure you want to delete this item?",
      actions: [{ text: 'No' }, { text: 'Yes', cssClass: 'k-primary' }],
      cssClass: 'utilPrompt'
    }

    this.dialogService.open(deleteConfirmSettings).result.pipe(take(1)).subscribe(result => {
      if (util.getDialogAction(result) === util.dialogAction.Yes)
        this.delete$.next(null);
    });
  }

  export(): void {
    this.exportClicked$.next(null);
  }

  dataStateChange(state: State): void {
    this.gridScrollPosition.topPos = 0;
    this.gridScrollPosition.leftPos = 0;
    if (!util.kendoFilterHasInvalidDate(state.filter)) {
      util.fixKendoQueryFilter(state.filter);
      this.state = state;
      this.refreshItems$.next(null);
    } else
      this.notify.error("Invalid date filter");
  }

  title$ = of('Holiday').pipe(
    tap((title) => util.trySetTitle(this.titleService, title))
  )

  filterSchedules$ = new BehaviorSubject<string>(null)

  schedules$ = this.filterSchedules$.pipe(util.filterIdNames(this.detailLoading$, this.requiredData$, 'schedules'));
}
