import { Maybe } from '@/core';
import { IGoodResponse } from '@/domains/pos/models/good.io';
import { SearchInputComponent } from '@/shared/components/search/search-input.component';
import { ChangeDetectionStrategy, Component, computed, inject, Input, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { Divider } from 'primeng/divider';
import { SelectButton } from 'primeng/selectbutton';
import { PosLandingStore, TViewType } from '../store/main.store';
import { PosGoodCategoriesComponent } from './categories.component';
import { PosGoodsGridViewComponent } from './grid-view.component';
import { PosGoodsListViewComponent } from './list-view.component';
import { PayloadFormDialogComponent } from './payloads';

@Component({
  selector: 'pos-goods',
  templateUrl: './goods.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [
    PosGoodCategoriesComponent,
    PosGoodsListViewComponent,
    SelectButton,
    FormsModule,
    PosGoodsGridViewComponent,
    SearchInputComponent,
    PayloadFormDialogComponent,
    Divider,
  ],
})
export class PosGoodsComponent {
  @Input() activeCategory = signal<Maybe<string>>(null);

  private readonly store = inject(PosLandingStore);

  constructor() {
    this.store.initial();
  }

  viewOptions = [
    { value: 'list', icon: 'pi pi-list' },
    { value: 'grid', icon: 'pi pi-th-large' },
  ];

  showPayloadForm = signal(false);
  selectedGoodToAdd = signal<Maybe<IGoodResponse>>(null);

  readonly activatedCategoryProducts = computed(() => this.store.activatedCategoryGoods());
  readonly stock = computed(() => this.store.goods());
  readonly inOrderGoods = computed(() => this.store.inOrderGoods());
  readonly priceInfo = computed(() => this.store.orderPricingInfo());
  readonly goods = computed(() => this.store.filteredGoods());
  readonly loading = computed(() => this.store.getGoodsLoading());

  get viewType() {
    return this.store.viewType();
  }
  set viewType(val: TViewType) {
    this.store.updateViewType(val);
  }

  onSearch(searchTerm: string) {
    this.store.updateSearchQuery(searchTerm);
    this.store.filterGoods();
  }

  onCategoryChange(categoryId: string) {
    this.store.changeActiveCategory(categoryId);
  }

  addGood(good: IGoodResponse) {
    this.showPayloadForm.set(false);
    this.selectedGoodToAdd.set(null);
    this.selectedGoodToAdd.set(good);
    queueMicrotask(() => this.showPayloadForm.set(true));
  }

  onClosePayloadForm() {
    this.showPayloadForm.set(false);
    this.selectedGoodToAdd.set(null);
  }
}
