import { AsyncPipe, CommonModule } from '@angular/common';
import { Component, inject } from '@angular/core';
import { Router, RouterModule } from '@angular/router';

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

import { IBlog } from '../../../../shared/interface/blog.interface';
import { IProduct } from '../../../../shared/interface/product.interface';
import { BlogState } from '../../../../shared/state/blog.state';
import { ProductState } from '../../../../shared/state/product.state';
import { GetSelectedBlogsAction } from '../../../action/blog.action';
import { GetMenuProductsAction } from '../../../action/product.action';
import { IMenu, IMenuModel } from '../../../interface/menu.interface';
import { IOption } from '../../../interface/theme-option.interface';
import { MenuService } from '../../../services/menu.service';
import { MenuState } from '../../../state/menu.state';
import { ThemeOptionState } from '../../../state/theme-option.state';
import { NoData } from '../no-data/no-data';
import { ProductBox } from '../product-box/product-box';
import { LinkBox } from './link-box/link-box';

@Component({
  selector: 'app-menu',
  imports: [CommonModule, TranslateModule, RouterModule, LinkBox, NoData, ProductBox, AsyncPipe],
  templateUrl: './menu.html',
  styleUrl: './menu.scss',
})
export class Menu {
  private store = inject(Store);
  private router = inject(Router);
  public menuService = inject(MenuService);

  product$: Observable<IProduct[]> = inject(Store).select(ProductState.dealProducts);
  blog$: Observable<IBlog[]> = inject(Store).select(BlogState.selectedBlogs);
  menu$: Observable<IMenuModel> = inject(Store).select(MenuState.menu);
  menuProduct$: Observable<IProduct[]> = inject(Store).select(ProductState.menuProducts);
  themeOption$: Observable<IOption> = inject(Store).select(
    ThemeOptionState.themeOptions,
  ) as Observable<IOption>;

  public menu: IMenu[] = [];
  public products: IProduct[];
  public blogs: IBlog[];

  constructor() {
    this.menu$.subscribe(menu => {
      const productIds = Array.from(new Set(this.concatDynamicProductKeys(menu, 'product_ids')));
      if (productIds && productIds.length) {
        this.store.dispatch(new GetMenuProductsAction({ ids: productIds?.join() }));

        this.menuProduct$.subscribe(products => {
          this.products = products.slice(0, 2);
        });
      }

      const blogIds = Array.from(new Set(this.concatDynamicProductKeys(menu, 'blog_ids')));
      if (blogIds && blogIds.length) {
        this.store.dispatch(new GetSelectedBlogsAction({ status: 1, ids: blogIds?.join() }));
        this.blog$.subscribe(blog => {
          this.blogs = blog.slice(0, 2);
        });

        // this.store.dispatch(new GetSelectedBlogsAction({status: 1, ids: blogIds?.join()})).subscribe({
        //   next: (val) => {
        //     this.blogs = val.blog.selectedBlogs.slice(0,2);
        //   }
        // })
      }
    });
  }

  redirect(path: string) {
    void this.router.navigateByUrl(path);
  }

  toggle(menu: IMenu) {
    if (!menu.active) {
      this.menu.forEach(item => {
        if (this.menu.includes(menu)) {
          item.active = false;
        }
      });
    }
    menu.active = !menu.active;
  }

  concatDynamicProductKeys(obj: any, keyName: string) {
    const result: number[] = [];
    function traverse(obj: any) {
      for (const key in obj) {
        if (key === keyName && Array.isArray(obj[key])) {
          result.push(...obj[key]);
        } else if (typeof obj[key] === 'object' && obj[key] !== null) {
          traverse(obj[key]);
        } else {
          if (key === keyName && obj.product_ids) {
            result.push(obj.product_ids);
          }
        }
      }
    }
    traverse(obj);
    return result;
  }
}
