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

@Component({
  selector: 'app-producerfee',
  templateUrl: './producerfee.component.html',
  encapsulation: ViewEncapsulation.None,
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [FAST_PAGE_COMMON, FAST_KENDO_COMMON]
})
export class ProducerFeeComponent {
  @ViewChild("grid", { read: ElementRef }) kendoGridEl: ElementRef;
  @ViewChild('docUploadTarget') docUploadElem: UploadComponent;
  @HostListener('window:resize', ['$event']) onResize() {
    //this function is empty but for some reason it helps the window to resize faster
  };

  constructor() {
    this.detailForm = this.getDetailForm();
    this.detailInitialValues = this.detailForm.getRawValue() as Detail;
    this.asOfForm = this.getAsOfForm();

    this.asOfDateChanged$ = this.asOfForm.get('asOfDate').valueChanges.pipe(
      tap(() => {
        setTimeout(() => { //waits for form controls to update before calling refresh
          this.refreshItems$.next(null);
        });
      }),
      shareReplay(1),
      catchError(err => {
        return util.handleError(err, this.messageService)
      }), retry(1)
    )

    this.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)
    )

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

    this.exportAction$ = this.exportClicked$.pipe(
      tap(() => {
        this.exporting$.next(true);
      }),
      switchMap(() => {
        return this.service.exportItems(this.state, this.asOfForm.value.asOfDate, 'ProducerFees.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)
    )

    this.producers$ = this.filterProducers$.pipe(util.filterIdNames(this.detailLoading$, this.requiredData$, 'producers'));
    this.feeTypes$ = this.filterfeeTypes$.pipe(util.filterIdNames(this.detailLoading$, this.requiredData$, 'feeTypes'));
  }

  util = util;
  icons = util.icons;
  isAddNew: boolean;
  secondContractDate: Date
  secondEffectiveDate: Date
  detailForm: util.FormModel<Detail>;
  asOfForm: util.FormModel<{ asOfDate: Date }>;
  gridScrollPosition: util.GridScrollPosition = { topPos: 0, leftPos: 0 };
  localRequiredData: RequiredData;
  hasModifyPermission = false;
  detailInitialValues: 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<util.SaveType>()
  delete$ = new Subject()
  exportClicked$ = new Subject()
  openSaveDialog$ = new Subject()
  saveDialog$ = new BehaviorSubject<boolean>(false)
  asOfDateChanged$: Observable<Date>;
  requiredData$: Observable<RequiredData>;
  items$: Observable<GridDataResult>;
  exportAction$: Observable<{ fileBlob: Blob, fileName: string }>;
  producers$: Observable<util.IdName[]>;
  feeTypes$: Observable<util.IdName[]>;
  filterProducers$ = new BehaviorSubject<string>(null)
  filterfeeTypes$ = new BehaviorSubject<string>(null)

  service = inject(ProducerFeeService);
  messageService = inject(MessageService);
  titleService = inject(Title);
  fb = inject(CustomFormBuilder);
  ref = inject(ChangeDetectorRef);
  dialogService = inject(DialogService);
  notify = inject(NotifyService);

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

  getDetailForm() {
    const fb = this.fb;
    const fg: util.FormModel<Detail> = fb.group({
      id: fb.ctr(0),
      producerId: fb.ctr(0, Validators.required),
      contractDate: fb.ctr(util.currentDate.toDate()),
      effectiveDate: fb.ctr(util.currentDate.toDate()),
      baseFee: fb.ctr(null, Validators.required),
      incFee: fb.ctr(null),
      feeTypeId: fb.ctr(0, Validators.required),
    });

    return fg;
  }

  getAsOfForm() {
    const fb = this.fb;
    const fg1: util.FormModel<{ asOfDate: Date }> = fb.group({
      asOfDate: fb.ctr(dayjs().toDate(), Validators.required)
    });

    return fg1;
  }

  //this updates localDetailLoading whenever detailLoading$ changes so that we can check the loading status in this class
  localDetailLoading = true;
  detailLoadingWatcher$ = this.detailLoading$.pipe(
    tap(isLoading => {
      this.localDetailLoading = isLoading;
    }),
    shareReplay(1)
  )

  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 = this.detailForm.getRawValue() 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.id);
    }),
    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 {
    util.saveGridScrollPos(this.kendoGridEl, this.gridScrollPosition);
    this.refreshDetail$.next(id);
    this.detailOpened$.next(true);
  }

  openSaveClicked$ = this.openSaveDialog$.pipe(
    tap(() => {
      this.saveDialog$.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.isAddNew = true;
    this.openDetail(0);
  }

  edit(dataItem: Item): void {
    this.isAddNew = false;
    this.openDetail(dataItem.Id);
  }

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

  saveNewInternal(instance: ProducerFeeComponent, saveType: util.SaveType): void {
    instance.detailForm.markAllAsTouched();
    if (instance.detailForm.valid) {
      instance.save$.next(saveType)
      this.closeInnerDetail(this);
    }
    else
      instance.notify.error("validation failed");
  }

  saveInternal(instance: ProducerFeeComponent, saveType: util.SaveType): void {
    instance.detailForm.markAllAsTouched();
    if (
      dayjs(instance.detailForm.value.effectiveDate).isSame(dayjs(this.secondEffectiveDate)) === false &&
      instance.detailForm.valid
    ) {
      instance.save$.next(saveType);
      this.closeInnerDetail(this);
    } else {
      instance.notify.error("validation failed");
    }
  }

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

  onInnerDetailClose() {
    this.closeInnerDetail(this);
  }

  closeInnerDetail(instance: ProducerFeeComponent) {
    instance.saveDialog$.next(false);
  }

  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;
    util.fixKendoQueryFilter(state.filter);
    this.state = state;
    this.refreshItems$.next(null);
  }

  refreshDropdowns() {
    this.refreshRequiredData$.next(util.RefreshType.SelfOnly);
  }

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

  getMaxWindowHeight() {
    return window.innerHeight;
  }

  getMaxWindowWidth() {
    return window.innerWidth;
  }
}
