import { DOCUMENT, ElementRef, inject, Injectable, Renderer2 } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

interface StateType {
  direction: string;
  theme: string;
  navigationStyles: string,   // vertical, horizontal
  menuStyles: string,                 // menu-click, menu-hover, icon-click, icon-hover
  layoutStyles: string,   // double-menu, detached, icon-overlay, icontext-menu, closed-menu, default-menu
  pageStyles: string,          // regular, classic, modern
  widthStyles: string,       // fullwidth, boxed
  menuPosition: string,          // fixed, scrollable
  headerPosition: string,        // fixed, scrollable
  menuColor: string,                  // light, dark, color, gradient, transparent
  headerColor: string,                // light, dark, color, gradient, transparent
  themePrimary: string,               // '58, 88, 146', '92, 144, 163', '161, 90, 223', '78, 172, 76', '223, 90, 90'
  themeBackground: string,
  backgroundImage: string,
};
@Injectable({
  providedIn: 'root'
})
export class AppStateService {
  private readonly localStorageKey = 'Ynex-ng'; // Customize this key
  private initialState: StateType = {
    theme: 'light',            // light, dark
    direction: 'ltr',               // ltr, rtl
    navigationStyles: 'vertical',   // vertical, horizontal
    menuStyles: '',                 // menu-click, menu-hover, icon-click, icon-hover
    layoutStyles: 'default',   // double-menu, detached, icon-overlay, icontext-menu, closed-menu, default-menu
    pageStyles: 'regular',          // regular, classic, modern
    widthStyles: 'fullwidth',       // fullwidth, boxed
    menuPosition: 'fixed',          // fixed, scrollable
    headerPosition: 'fixed',        // fixed, scrollable
    menuColor: 'dark',                  // light, dark, color, gradient, transparent
    headerColor: 'light',                // light, dark, color, gradient, transparent
    themePrimary: '',          // '58, 88, 146', '92, 144, 163', '161, 90, 223', '78, 172, 76', '223, 90, 90'
    themeBackground: '',
    backgroundImage: '',         // bgimg1, bgimg2, bgimg3, bgimg4, bgimg5
  } // Store initial state
  private stateSubject = new BehaviorSubject<StateType>(this.initialState); // Use any for initial null value
  state$ = this.stateSubject.asObservable();
  private document = inject(DOCUMENT);
  navigationStyles: any;
  private html = this.document.documentElement;

  constructor() {

    const initialState: StateType = this.getInitialStateFromLocalStorage();
    // this.initializeState();
    this.stateSubject.next(initialState);

  }

  private getInitialStateFromLocalStorage(): StateType {
    try {
      const storedState = localStorage.getItem(this.localStorageKey);
      if (storedState) {
        return JSON.parse(storedState);
      }
    } catch (error) {
      console.error('Error retrieving initial state from local storage:', error);
    }
    return this.initialState;
  }




  getupdateState() {
    const currentState = this.stateSubject.getValue();
    return currentState
  }

  updateState(newState?: Partial<any>) { // Use any for partial updates
    const currentState = this.stateSubject.getValue(); // Get current state

    if (!currentState) {

      // Handle initial update case (no state emitted yet)
      this.updateStateAndEmit(newState);
      return;
    }
    if (newState) {

      const updatedState = { ...currentState, ...newState }; // Merge updates
      this.updateStateAndEmit(updatedState); // Update and emit combined state
    } else {
      this.updateStateAndEmit(currentState);

      return;
    }
  }

  private state: { [key: string]: any } = {};
  getState(menuStyles: string): any {
    return this.state[menuStyles];
  }
  private applyThemeBackgroundSpecificChanges(background: any) {

    this.html?.style.setProperty('--color-bodybg', background.main);
    this.html?.style.setProperty('--color-bodybg2', background.secondary);
    this.html?.style.setProperty('--color-light', background.accent);
    this.html?.style.setProperty('--color-formcontrolbg', `rgba(${background.accent})`);
    this.html?.style.setProperty('--color-inputborder', background.overlay);
    this.html?.style.setProperty('--color-gray3', background.primary);
    this.applythemeSpecificChanges(background.theme);
  }


  private applyDirectionSpecificChanges(direction: string) {


    this.html?.setAttribute('dir', direction);

  }
  private applythemeSpecificChanges(theme: string) {


    this.html?.setAttribute('class', theme);  //setting theme style
    this.html?.setAttribute('data-header-styles', theme); //setting header style





  }



  private applyNavigationStylesSpecificChanges(navigationStyles: string) {



    this.html?.setAttribute('data-nav-layout', navigationStyles);
    if (navigationStyles == 'horizontal') {
      this.html?.setAttribute('data-nav-style', 'menu-click');
      this.html?.removeAttribute('data-vertical-style');

    }
  }
  private applyMenuStylesSpecificChanges(menuStyles: string) {



    this.html?.setAttribute('data-nav-style', menuStyles);
    this.html?.setAttribute('data-toggled', menuStyles + '-closed');
    this.html?.removeAttribute('data-vertical-style');
  }
  private applyLayoutStylesSpecificChanges(layoutStyles: string) {

    this.html?.setAttribute('data-vertical-style', layoutStyles);
    this.html?.removeAttribute('data-nav-style');
    switch (layoutStyles) {
      case 'default':
        this.html?.setAttribute('data-vertical-style', 'overlay');
        this.html?.setAttribute('data-toggled', '');
        break;
      case 'closed':
        this.html?.setAttribute('data-toggled', 'close-menu-close');
        break;
      case 'icontext':
        this.html?.setAttribute('data-toggled', 'icon-text-close');
        break;
      case 'overlay':
        this.html?.setAttribute('data-toggled', 'icon-overlay-close');
        break;
      case 'detached':
        this.html?.setAttribute('data-toggled', 'detached-close');
        break;
      case 'doublemenu':
        this.html?.setAttribute('data-toggled', 'double-menu-open');
        break;
    }
    if (layoutStyles === 'icon-text') {
      this.html?.setAttribute('icon-text', 'open');
    } else {
      // If not 'icon-text', remove the icon-text attribute
      this.html?.removeAttribute('icon-text');
    }
  }
  private applypageStylesSpecificChanges(pageStyles: string) {

    this.html?.setAttribute('data-page-style', pageStyles);

    const slideRight = document.querySelector('.slide-right') as HTMLElement | null;
    if (slideRight) {
      // If the element exists, toggle the 'd-none' class
      if (slideRight.classList.contains('d-none')) {
        slideRight.classList.remove('d-none');
      } else {
        slideRight.classList.add('d-none');
      }
    } else {
      // If the element does not exist (is null), create a safe fallback by adding 'd-none'
      const dummySlideRight = document.createElement('div');
      dummySlideRight.classList.add('slide-right', 'd-none'); // Add classes to the new element
      document.body.appendChild(dummySlideRight); // Append it to the DOM as a fallback
    }
  }
  private applywidthStylesSpecificChanges(widthStyles: string) {

    this.html?.setAttribute('data-width', widthStyles);
  }
  private applymenuPositionSpecificChanges(menuPosition: string) {

    this.html?.setAttribute('data-menu-position', menuPosition);
  }
  private applyheaderPositionSpecificChanges(headerPosition: string) {

    this.html?.setAttribute('data-header-position', headerPosition);
  }
  private applyheaderColorSpecificChanges(headerColor: string) {

    this.html?.setAttribute('data-header-styles', headerColor);
  }
  private applymenuColorSpecificChanges(menuColor: string) {

    this.html?.setAttribute('data-menu-styles', menuColor);
  }
  private applyPrimarySpecificChanges(primary: string) {

    this.html?.style.setProperty('--color-primaryrgb', primary);
    this.html?.style.setProperty('--color-primary', primary);
  }
  private applybackgroundImageSpecificChanges(backgroundImage: string) {

    this.html?.setAttribute('bg-img', backgroundImage);
  }




  public applyReset() {

    if (this.html) {
      this.html?.style.removeProperty('--color-bodybg');
      this.html?.style.removeProperty('--color-gray3');
      this.html?.style.removeProperty('--color-bodybg2');
      this.html?.style.removeProperty('--color-light');
      this.html?.style.removeProperty('--color-formcontrolbg');
      this.html?.style.removeProperty('--color-inputborder');
      this.html?.style.removeProperty('--color-primary');
      this.html?.style.removeProperty('--color-primaryrgb');

    }
    this.html?.removeAttribute('bg-img');
    this.html?.setAttribute('data-vertical-style', 'overlay');
    this.stateSubject.next(this.initialState);
    this.updateStateAndEmit(this.initialState);
    localStorage.clear();

    if (window.innerWidth <= 992) {
      this.html?.setAttribute('data-toggled', 'close');
    }
  }

  private updateStateAndEmit(state: any) {
    // Conditional logic based on direction changes

    const currentState = this.stateSubject.getValue(); // Get current state
    // Conditional logic based on theme changes
    if (state['theme']) {

      this.applythemeSpecificChanges(state['theme']);
    }
    if (state['direction']) {

      this.applyDirectionSpecificChanges(state['direction']);
    }
    // Conditional logic based on theme changes
    if (state['navigationStyles']) {
      this.applyNavigationStylesSpecificChanges(state['navigationStyles']);
    }
    // Conditional logic based on theme changes
    if (state['menuStyles'] && !state['layoutStyles']) {
      this.applyMenuStylesSpecificChanges(state['menuStyles']);
    }
    if (state['layoutStyles'] && !state['menuStyles']) {
      this.applyLayoutStylesSpecificChanges(state['layoutStyles']);
    }
    if (state['pageStyles']) {
      this.applypageStylesSpecificChanges(state['pageStyles']);
    }
    if (state['widthStyles']) {
      this.applywidthStylesSpecificChanges(state['widthStyles']);
    }
    if (state['menuPosition']) {
      this.applymenuPositionSpecificChanges(state['menuPosition']);
    }
    if (state['headerPosition']) {
      this.applyheaderPositionSpecificChanges(state['headerPosition']);
    }
    if (state['themePrimary']) {
      this.applyPrimarySpecificChanges(state['themePrimary']);
    }
    if (state['themeBackground']) {
      this.applyThemeBackgroundSpecificChanges(state['themeBackground']);
    }
    if (state['headerColor']) {
      this.applyheaderColorSpecificChanges(state['headerColor']);
    }
    if (state['menuColor']) {
      this.applymenuColorSpecificChanges(state['menuColor']);
    }
    if (state['backgroundImage']) {
      this.applybackgroundImageSpecificChanges(state['backgroundImage']);
    }

    this.stateSubject.next(state);
    this.updateLocalStorage(state);
  }

  private updateLocalStorage(state: any) {
    try {
      localStorage.setItem(this.localStorageKey, JSON.stringify(state));
    } catch (error) {
      console.error('Error saving state to local storage:', error);
    }
  }
}
