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

import { Action, Selector, State, StateContext } from '@ngxs/store';
import { tap } from 'rxjs';

import { GetHomePageAction, GetThemesAction } from '../action/theme.action';
import { ThemeOptionService } from '../services/theme-option.service';
import { ThemeService } from '../services/theme.service';

export class ThemesStateModel {
  homePage: object | null;
  activeTheme: string;
}

@State<ThemesStateModel>({
  name: 'theme',
  defaults: {
    homePage: null,
    activeTheme: '',
  },
})
@Injectable()
export class ThemeState {
  private themeService = inject(ThemeService);
  private themeOptionService = inject(ThemeOptionService);

  @Selector()
  static homePage(state: ThemesStateModel) {
    return state.homePage;
  }

  @Selector()
  static activeTheme(state: ThemesStateModel) {
    return state.activeTheme;
  }

  @Action(GetThemesAction)
  getThemes(ctx: StateContext<ThemesStateModel>) {
    return this.themeService.getThemes().pipe(
      tap({
        next: result => {
          var activeTheme: string = '';
          result.data.map(theme => {
            if (theme.status === 1) {
              activeTheme = theme.slug;
            }
          });
          ctx.patchState({
            homePage: result,
            activeTheme: activeTheme,
          });
        },
        error: err => {
          throw new Error(err?.error?.message);
        },
      }),
    );
  }

  @Action(GetHomePageAction)
  getHomePage(ctx: StateContext<ThemesStateModel>, action: GetHomePageAction) {
    this.themeOptionService.preloader = true;
    return this.themeService.getHomePage(action?.slug).pipe(
      tap({
        next: result => {
          ctx.patchState({
            homePage: result,
          });
        },
        error: err => {
          throw new Error(err?.error?.message);
        },
        complete: () => {
          this.themeOptionService.preloader = false;
        },
      }),
    );
  }
}
