import { Component, ChangeDetectionStrategy, ChangeDetectorRef, ViewChild, ElementRef, ViewEncapsulation, HostListener, inject } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { tap, 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, promptAction } from '../_shared/services/message.service';
import { Validators } from '@angular/forms';
import { CustomFormBuilder } from '../_shared/services/custom-form-builder.service';
import { } from '@progress/kendo-angular-dialog';
import { NotifyService } from '../_shared/services/notify.service';
import * as util from '../_shared/utils/util';
import { SuccessEvent, ErrorEvent, UploadComponent } from '@progress/kendo-angular-upload';
import { SalesTaxExemptionService, Item, Detail, SaveType, RequiredData } from './sales-tax-exemption.service';
import { FAST_KENDO_COMMON, FAST_PAGE_COMMON } from '../app.config';

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

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

  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[] = [];
  docSaveUrl = `${window.location.origin}/api/SalesTaxExemption/UploadDoc`;

  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()
  downloadDoc$ = new Subject<util.DocItem>()

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

  getDetailForm() {
    const fb = this.fb;
    const fg: util.FormModel<Detail> = fb.group({
      salesTaxExemptionId: fb.ctr(0, Validators.required),
      companyId: fb.ctr(null, Validators.required),
      stateId: fb.ctr(null, Validators.required),
      effectiveDate: fb.ctr(null),
      expirationDate: fb.ctr(null, Validators.required),
      certificates: fb.ctr([]),
      notes: fb.ctr(null)
    });

    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;
    }),
    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, 'SalesTaxExemptions.xlsx');
    }),
    tap(res => {
      util.openOrSaveFile(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 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: 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.salesTaxExemptionId);
    }),
    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);
  }

  onDetailClosing() {
    util.onDetailChanging(this.detailForm, this.messageService, 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);
  }

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

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

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

  delete(): void {
    const message = "Are you sure you want to delete this item?";
    this.messageService.prompt(message, "Please confirm", 'Yes-No').then(result => {
      if (result === promptAction.Yes)
        this.delete$.next(null);
    });
  }

  downloadDocResult$ = this.downloadDoc$.pipe(
    filter(docItem => {
      return docItem && docItem.fileNameOnDisk !== null;
    }),
    switchMap(fileNamePair => {
      return this.service.downloadDoc(fileNamePair.fileNameOriginal, fileNamePair.fileNameOnDisk);
    }),
    tap(res => {
      util.openOrSaveFile(res.fileBlob, res.fileName);
    }),
    catchError(err => {
      return util.handleError(err, this.messageService);
    }), retry(10)
  )

  docComplete() {
    this.docUploadElem.clearFiles();
  }

  downloadDoc(doc: util.DocItem) {
    this.downloadDoc$.next(doc)
  }

  removeDoc(doc: util.DocItem) {
    const docs: util.DocItem[] = this.detailForm.get('certificates').value;
    const indexToRemove = docs.findIndex(x => x.fileNameOnDisk === doc.fileNameOnDisk);
    docs.splice(indexToRemove, 1);
    this.detailForm.patchValue({ certificates: docs });
    this.detailForm.markAsDirty();
  }

  docUploadSuccess(value: SuccessEvent) {
    const newdocitems: util.DocItem[] = value.response.body;
    let docs: util.DocItem[] = this.detailForm.get('certificates').value;
    if (docs)
      docs = docs.concat(newdocitems);
    else
      docs = newdocitems;
    this.detailForm.patchValue({ certificates: docs });
    this.detailForm.markAsDirty();
  }

  docUploadError(value: ErrorEvent) {
    util.handleError(value.response, this.messageService);
  }

  uploadProgress() {
    this.ref.detectChanges();
  }

  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('Sales Tax Exemption').pipe(
    tap((title) => util.trySetTitle(this.titleService, title))
  )

  filterCompanies$ = new BehaviorSubject<string>(null)

  companies$ = this.filterCompanies$.pipe(util.filterIdNames(this.detailLoading$, this.requiredData$, 'companies'));

  filterStates$ = new BehaviorSubject<string>(null)

  states$ = this.filterStates$.pipe(util.filterIdNames(this.detailLoading$, this.requiredData$, 'states'));
}
