import {Component, OnDestroy, OnInit} from '@angular/core';
import {CommonModule} from '@angular/common';
import {Store} from '@ngrx/store';
import {Subscription} from 'rxjs';
import {ActionTypes, StateInterface} from '../../reducers';

@Component({
  selector: 'app-theme-selector',
  standalone: true,
  imports: [CommonModule],
  templateUrl: './theme-selector.html',
  styleUrl: './theme-selector.scss'
})
export class ThemeSelector implements OnInit, OnDestroy {
  activeTheme: string = '';
  themesList: string[] = [];
  private storeSubscription: Subscription | null = null;

  constructor(private store: Store<StateInterface>) {
  }

  ngOnInit(): void {
    // Subscribe to the store to get the active theme and themes list
    this.storeSubscription = this.store.select(state => state.app)
      .subscribe(app => {
        // If the active theme has changed, update the body class
        if (this.activeTheme !== app.activeTheme) {
          // Remove the previous theme class if it exists
          if (this.activeTheme) {
            document.body.classList.remove(`app-theme-${this.activeTheme}`);
          }
          document.body.classList.add(`app-theme-${app.activeTheme}`);
          this.activeTheme = app.activeTheme;
        }
        this.themesList = app.themesList;
      });
  }

  ngOnDestroy(): void {
    // Unsubscribe to prevent memory leaks
    if (this.storeSubscription) {
      this.storeSubscription.unsubscribe();
    }

    // Remove the theme class from the body when the component is destroyed
    if (this.activeTheme) {
      document.body.classList.remove(this.activeTheme);
    }
  }

  // Method to switch to the next theme
  switchToNextTheme(): void {
    this.store.dispatch({type: ActionTypes.SWITCH_TO_NEXT_THEME});
  }
}
