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 { NotifyService } from '../_shared/services/notify.service';
import * as util from '../_shared/utils/util';
import { SalesTaxRateService, Item, Detail, SaveType, RequiredData } from './sales-tax-rate.service';
import { FAST_KENDO_COMMON, FAST_PAGE_COMMON } from '../app.config';
@Component({
  selector: 'app-SalesTaxRate',
  templateUrl: './sales-tax-rate.component.html',
  encapsulation: ViewEncapsulation.None,
  changeDetection: ChangeDetectionStrategy.OnPush,
  standalone: true,
  imports: [FAST_KENDO_COMMON, FAST_PAGE_COMMON]
})
export class SalesTaxRateComponent {
  @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
  };

  service = inject(SalesTaxRateService);
  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[] = [];
  percentInputFormat = '#,.#####%';

  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)
  refreshCountyForState$ = new BehaviorSubject(null)

  save$ = new Subject<SaveType>()
  delete$ = new Subject()
  exportClicked$ = new Subject()

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

  getDetailForm() {
    const fb = this.fb;
    const fg: util.FormModel<Detail> = fb.group({
      salesTaxRateId: fb.ctr(0, Validators.required),
      stateId: fb.ctr(null, Validators.required),
      rate: fb.ctr(null, Validators.required),
      inactiveDate: fb.ctr(null),
      countyId: fb.ctr(0, 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;
    }),
    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, 'SalesTaxRates.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)
  )

  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();
      this.refreshCountyForState$.next(null);
    }),
    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.salesTaxRateId);
    }),
    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.SalesTaxRateId);
  }

  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);
    });
  }

  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);
    this.refreshCountyForState$.next(null);
  }

  subCountyForState$ = this.refreshCountyForState$.pipe(
    map(() => {
      const selectedStateId = this.detailForm.get('stateId').value ?? null;
      const filteredCounties = this.localRequiredData.counties.filter(x => x.stateId === selectedStateId);

      const countyId = this.detailForm.get('countyId').getRawValue();
      if (filteredCounties && filteredCounties.findIndex(x => x.countyId === countyId) === -1)
        this.detailForm.patchValue({ countyId: null }, { emitEvent: false });

      if (filteredCounties.length === 1)
        this.detailForm.patchValue({ countyId: filteredCounties[0].countyId }, { emitEvent: false });

      return filteredCounties;
    }),
    shareReplay(1),
    catchError(err => {
      return util.handleError(err, this.messageService)
    }), retry(10)
  )

  stateChanged$ = this.detailForm.get('stateId').valueChanges.pipe(
    filter(() => {
      return !this.detailLoading$.value;
    }),
    tap(() => {
      this.refreshCountyForState$.next(null);
    }),
    shareReplay(1)
  )

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

  filterState$ = new BehaviorSubject<string>(null)
  states$ = this.filterState$.pipe(util.filterIdNames(this.detailLoading$, this.requiredData$, 'states'));

  filterCounty$ = new BehaviorSubject<string>(null)
  county$ = this.filterCounty$.pipe(util.filterSpecials(this.detailLoading$, this.subCountyForState$, null, 'countyName'));
}
