import { CommonModule } from '@angular/common';
import { Component, inject } from '@angular/core';
import { FormControl, ReactiveFormsModule } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';

import { TranslateModule } from '@ngx-translate/core';
import { Store } from '@ngxs/store';
import { Observable, debounceTime, distinctUntilChanged } from 'rxjs';

import { GetProductsAction } from '../../../shared/action/product.action';
import { Breadcrumb } from '../../../shared/components/widgets/breadcrumb/breadcrumb';
import { Button } from '../../../shared/components/widgets/button/button';
import { NoData } from '../../../shared/components/widgets/no-data/no-data';
import { ProductBox } from '../../../shared/components/widgets/product-box/product-box';
import { SkeletonProductBox } from '../../../shared/components/widgets/product-box/widgets/skeleton-product-box/skeleton-product-box';
import * as data from '../../../shared/data/owl-carousel';
import { IBreadcrumb } from '../../../shared/interface/breadcrumb';
import { Params } from '../../../shared/interface/core.interface';
import { IProduct, IProductModel } from '../../../shared/interface/product.interface';
import { IOption } from '../../../shared/interface/theme-option.interface';
import { ProductState } from '../../../shared/state/product.state';
import { ThemeOptionState } from '../../../shared/state/theme-option.state';
import { ProductService } from './../../../shared/services/product.service';

@Component({
  selector: 'app-search',
  imports: [
    CommonModule,
    TranslateModule,
    ReactiveFormsModule,
    Breadcrumb,
    Button,
    SkeletonProductBox,
    ProductBox,
    NoData,
  ],
  templateUrl: './search.html',
  styleUrl: './search.scss',
})
export class Search {
  public productService = inject(ProductService);
  private store = inject(Store);
  public router = inject(Router);
  private route = inject(ActivatedRoute);

  public breadcrumb: IBreadcrumb = {
    title: 'Search',
    items: [{ label: 'Search', active: true }],
  };

  product$: Observable<IProductModel> = inject(Store).select(ProductState.product);
  themeOption$: Observable<IOption> = inject(Store).select(
    ThemeOptionState.themeOptions,
  ) as Observable<IOption>;

  public products: IProduct[];
  public search = new FormControl();
  public totalItems: number = 0;
  public gridClass: string =
    'row g-sm-4 g-3 row-cols-2 row-cols-md-3 cols-lg-4 row-cols-xxl-6 product-list-section';
  public skeletonItems = Array.from({ length: 12 }, (_, index) => index);
  public productSlider6ItemMargin = data.productSlider6ItemMargin;
  public filter: Params = {
    page: 1, // Current page number
    paginate: 12, // Display per page,
    status: 1,
    search: '',
  };

  constructor() {
    this.route.queryParams.subscribe(params => {
      if (params['search']) {
        this.filter['search'] = params['search'];
        this.search.patchValue(params['search'] ? params['search'] : '');
      }

      this.store.dispatch(new GetProductsAction(this.filter));

      this.product$.subscribe(product => {
        this.products = product.data;
      });
    });
  }

  ngOnInit() {
    this.search.valueChanges
      .pipe(debounceTime(300), distinctUntilChanged()) // Adjust the debounce time as needed (in milliseconds)
      .subscribe(inputValue => {
        if (inputValue.length == 0) {
          void this.router.navigate([], {
            relativeTo: this.route,
            queryParams: {
              search: inputValue,
            },
          });
          this.filter['search'] = inputValue;
        }
      });

    this.themeOption$.subscribe(option => {
      if (option?.product?.product_box_variant === 'digital') {
        this.gridClass =
          'row g-sm-4 g-3 row-custom-col-1 row-cols-1 row-cols-sm-2 cols-lg-4 row-cols-xxl-4 product-list-section';
      }
    });
  }

  searchProduct() {
    void this.router.navigate([], {
      relativeTo: this.route,
      queryParams: {
        search: this.search.value,
      },
    });
    this.filter['search'] = this.search.value;
  }
}
