import { FilterState } from '../../../../../../core/store/state/filter.state';
import {
  Component,
  OnInit,
  Input,
  Output,
  EventEmitter,
  OnDestroy,
  ViewChild,
  ElementRef,
  ChangeDetectionStrategy,
  HostListener,
  ChangeDetectorRef,
} from '@angular/core';
import { Filter } from '../../../../../../core/models/filter.model';
import {
  SelectFilterById,
  UnselectFilterById,
  ToggleFilterItemByName,
  AddSelectedFilter,
} from '../../../../../../core/store/actions/filter.actions';
import { FilterItem } from 'apps/sales/src/app/core/models/filter-item.model';
import { Store } from '@ngxs/store';
import { fadeInAnimation } from './fadeIn.animation';
import { Subject, of, Observable } from 'rxjs';
import { takeUntil, filter, tap, take } from 'rxjs/operators';
import { SharedSelectors } from 'apps/sales/src/app/core/store/selectors/shared.selectors';
import { ProductUtilService } from 'apps/sales/src/app/core/services/product-util.service';
import { AppService } from 'apps/sales/src/app/core/services/app.service';
import { isNullOrUndefined } from 'util';
import { Side } from '@libs/ui/lib/small-double-choice-switch';
import { FilterType } from 'apps/sales/src/app/core/models/filter-type.enum';

@Component({
  selector: 'app-filter-item',
  templateUrl: './filter-item.component.html',
  styleUrls: ['./filter-item.component.scss'],
  animations: [fadeInAnimation],
})
export class FilterItemComponent implements OnInit, OnDestroy {
  @Input() index: number;
  @Input() selectedFilterMode: Side;
  destroy$ = new Subject();
  filter: Filter;
  items: FilterItem[];
  isIpad = false;
  inactive = true;
  prevTopPosition = 0;
  topPosition = 0;
  setContanerRightPosition = false;
  allowRecoveryScroll = false;
  @ViewChild('optionContainer') optionContainer: ElementRef<any>;

  @Output() confirmed = new EventEmitter();

  @ViewChild('menu') menu: ElementRef<any>;

  get containerHeight() {
    if (this.menu) {
      const menuTop = this.menu.nativeElement.offsetTop;
      const winowHeight = window.innerHeight;
      const containerHeight = winowHeight - menuTop - 133;
      const value = containerHeight;
      const allItemsHeight = (Math.round((value - 90) / 47) + 2) * 47;
      return allItemsHeight - (this.isIpad ? 20 : 5);
    }
    return 0;
  }

  get filterType() {
    if (this.selectedFilterMode) {
      return this.selectedFilterMode === Side.RIGHT ? FilterType.Negative : FilterType.Default;
    }
  }

  constructor(
    private store: Store,
    private productUtils: ProductUtilService,
    private appService: AppService,
    private cdrf: ChangeDetectorRef
  ) {}

  toggleMenu(id: string) {
    const action = this.filter.expanded ? new UnselectFilterById(id) : new SelectFilterById(id);
    this.store.dispatch(action);
    if (!this.filter.expanded) {
      this.store.dispatch(new AddSelectedFilter(this.filter));
      this.productUtils.enableScrolling();
    } else {
      this.productUtils.disableScrolling();
    }
    this.repositionOptionContainerIfNeeded();
  }

  repositionOptionContainerIfNeeded() {
    const windowWidth = window.innerWidth;
    setTimeout(() => {
      if (this.optionContainer) {
        const containerCoordinates = this.optionContainer.nativeElement.getBoundingClientRect();
        const isContainerOffScreen = containerCoordinates.left + containerCoordinates.width + 10 >= windowWidth;
        if (isContainerOffScreen) {
          this.setContanerRightPosition = true;
          if (this.cdrf) {
            this.cdrf.detectChanges();
          }
        }
      }
    }, 1);
  }

  filterConfirm(filterToConfirm: Filter) {
    this.toggleMenu(filterToConfirm.id);
    if (this.inactive) {
      return;
    }
    this.confirmed.emit(true);
  }

  selectItem(item: FilterItem) {
    this.allowRecoveryScroll = true;
    if (this.filter.id === 'orderBy') {
      this.filter.items
        .filter((t) => t.selected === true)
        .forEach((t) => {
          this.store.dispatch(new ToggleFilterItemByName(t.name));
        });
    }
    this.store.dispatch(new ToggleFilterItemByName(item.name));
  }

  ngOnInit() {
    this.isIpad = this.appService.isIPadEnv();
    this.getFilters();
  }

  getFilters() {
    this.store
      .select(SharedSelectors.getFilterIndex(this.index))
      .pipe(
        filter((data) => !isNullOrUndefined(data)),
        takeUntil(this.destroy$)
      )
      .subscribe((f: Filter) => {
        this.filter = { ...f };
        this.items = [...f.items];
        this.inactive = true;
        if (f) {
          f.items.forEach((item) => {
            if (item.selected) {
              this.inactive = false;
            }
          });
        }
      });
  }

  @HostListener('window:scroll', ['$event'])
  scrollHandler(event) {
    this.prevTopPosition = this.topPosition;
    this.topPosition = event.target.scrollTop;
    if (this.optionContainer && this.topPosition - this.prevTopPosition > 30 && this.allowRecoveryScroll) {
      this.allowRecoveryScroll = false;
      this.optionContainer.nativeElement.scrollTo({ top: this.prevTopPosition, behavior: 'auto' });
    }
  }

  ngOnDestroy() {
    this.destroy$.next();
  }
}
