import { CommonModule } from '@angular/common';
import { Component, inject, Input, input } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

import { Store } from '@ngxs/store';
import { forkJoin, Observable } from 'rxjs';

import { GetBlogsAction } from '../../../shared/action/blog.action';
import { GetBrandsAction } from '../../../shared/action/brand.action';
import {
  GetCategoryProductsAction,
  GetProductByIdsAction,
} from '../../../shared/action/product.action';
import { GetStoresAction } from '../../../shared/action/store.action';
import { ImageLink } from '../../../shared/components/widgets/image-link/image-link';
import { Title } from '../../../shared/components/widgets/title/title';
import * as data from '../../../shared/data/owl-carousel';
import { IProduct } from '../../../shared/interface/product.interface';
import { IOption } from '../../../shared/interface/theme-option.interface';
import { IRome } from '../../../shared/interface/theme.interface';
import { ThemeOptionService } from '../../../shared/services/theme-option.service';
import { ProductState } from '../../../shared/state/product.state';
import { ThemeOptionState } from '../../../shared/state/theme-option.state';
import { Banner } from '../widgets/banner/banner';
import { Blog } from '../widgets/blog/blog';
import { Brand } from '../widgets/brand/brand';
import { ThemeCategories } from '../widgets/categories/categories';
import { CategoryProductFilter } from '../widgets/category-product-filter/category-product-filter';
import { FourColumnProduct } from '../widgets/four-column-product/four-column-product';
import { HomeBanner } from '../widgets/home-banner/home-banner';
import { INewsletter } from '../widgets/newsletter/newsletter';
import { Product } from '../widgets/product/product';
import { TopSeller } from '../widgets/top-seller/top-seller';

@Component({
  selector: 'app-rome',
  imports: [
    CommonModule,
    HomeBanner,
    Title,
    ThemeCategories,
    Banner,
    CategoryProductFilter,
    TopSeller,
    ImageLink,
    FourColumnProduct,
    Product,
    Blog,
    Brand,
    INewsletter,
  ],
  templateUrl: './rome.html',
  styleUrl: './rome.scss',
})
export class Rome {
  private themeOptionService = inject(ThemeOptionService);
  private route = inject(ActivatedRoute);
  private store = inject(Store);

  @Input() data?: IRome;
  readonly slug = input<string>();

  categoryProduct$: Observable<IProduct[]> = inject(Store).select(
    ProductState.categoryProducts,
  ) as Observable<IProduct[]>;
  themeOption$: Observable<IOption> = inject(Store).select(
    ThemeOptionState.themeOptions,
  ) as Observable<IOption>;

  public categorySlider = data.categorySlider9;
  public productSlider6ItemMargin = data.productSlider6ItemMargin;
  public customOptionsItem4 = data.customOptionsItem4;
  public productFilterIds: number[] = [];
  public selectedCategoryId: number;
  public showProductBox: number = 6;

  ngOnInit() {
    if (this.data?.slug == this.slug()) {
      // Get Products
      const getProducts$ = this.store.dispatch(
        new GetProductByIdsAction({
          status: 1,
          paginate: this.data?.content?.products_ids.length,
          ids: this.data?.content?.products_ids?.join(','),
        }),
      );
      const getBrand$ = this.store.dispatch(
        new GetBrandsAction({
          status: 1,
          ids: this.data?.content?.brands?.brand_ids?.join(),
        }),
      );
      const getStore$ = this.store.dispatch(
        new GetStoresAction({
          status: 1,
          ids: this.data?.content?.seller?.store_ids?.join(),
        }),
      );
      const getBlogs$ = this.store.dispatch(
        new GetBlogsAction({
          status: 1,
          ids: this.data?.content?.featured_blogs?.blog_ids?.join(','),
        }),
      );

      const getCatProducts$ = this.store.dispatch(
        new GetCategoryProductsAction({
          category_ids: this.data?.content?.categories_products?.category_ids?.join(','),
        }),
      );

      // Skeleton Loader
      document.body.classList.add('skeleton-body');

      forkJoin([getProducts$, getBlogs$, getCatProducts$, getBrand$, getStore$]).subscribe({
        complete: () => {
          document.body.classList.remove('skeleton-body');
          this.themeOptionService.preloader = false;
        },
      });

      if (
        this.data?.content?.categories_products &&
        this.data?.content?.categories_products?.category_ids?.length
      ) {
        this.selectCategory(this.data?.content?.categories_products?.category_ids[0]);
      }
    }

    this.route.queryParams.subscribe(_params => {
      if (this.route.snapshot.data['data'].theme_option.productBox === 'digital') {
        if (
          this.productSlider6ItemMargin &&
          this.productSlider6ItemMargin.responsive &&
          this.productSlider6ItemMargin.responsive['1180']
        ) {
          this.productSlider6ItemMargin = {
            ...this.productSlider6ItemMargin,
            items: 4,
            responsive: {
              ...this.productSlider6ItemMargin.responsive,
              1180: {
                items: 4,
              },
            },
          };
          this.showProductBox = 4;
        }
      } else {
        if (
          this.productSlider6ItemMargin &&
          this.productSlider6ItemMargin.responsive &&
          this.productSlider6ItemMargin.responsive['1180']
        ) {
          this.productSlider6ItemMargin = {
            ...this.productSlider6ItemMargin,
            items: 6,
            responsive: {
              ...this.productSlider6ItemMargin.responsive,
              1180: {
                items: 6,
              },
            },
          };
          this.showProductBox = 6;
        }
      }
    });
  }

  selectCategory(id: number) {
    this.selectedCategoryId = id;
    this.categoryProduct$.subscribe(products => {
      this.productFilterIds = products
        .filter(product => product?.categories?.map(category => category.id).includes(id))
        ?.map(product => product.id)
        .slice(0, 5);
    });
  }
}
