import { inject, Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, Resolve } from '@angular/router';

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

import { UpdateProductBoxAction } from '../action/theme-option.action';
import { IOption } from '../interface/theme-option.interface';
import { ThemeOptionService } from '../services/theme-option.service';
import { ThemeOptionState } from '../state/theme-option.state';

@Injectable({
  providedIn: 'root',
})
export class HomeResolver implements Resolve<unknown> {
  private store = inject(Store);
  private themeOptionService = inject(ThemeOptionService);

  public theme: string;

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

  resolve(route: ActivatedRouteSnapshot): Observable<unknown> {
    this.theme = route.queryParams['theme'];
    if (this.theme === 'paris' || this.theme === 'tokyo') {
      this.themeOptionService.productBox = 'basic';
    } else if (this.theme === 'berlin' || this.theme === 'denver') {
      this.themeOptionService.productBox = 'standard';
    } else if (this.theme === 'osaka' || this.theme === 'rome') {
      this.themeOptionService.productBox = 'classic';
    } else if (this.theme === 'cairo') {
      this.themeOptionService.productBox = 'digital';
    } else if (this.theme === 'madrid' || this.theme === 'moscow') {
      this.themeOptionService.productBox = 'premium';
    } else {
      this.themeOption$.subscribe(theme => {
        this.themeOptionService.productBox = theme?.product
          ? theme?.product?.product_box_variant
          : 'basic';
      });
    }
    return this.store.dispatch(new UpdateProductBoxAction(this.themeOptionService.productBox));
  }
}
