import { Component, inject, Inject, DOCUMENT } from '@angular/core';
import { Meta } from '@angular/platform-browser';
import { Router, RouterOutlet } from '@angular/router';

import { NgbRatingConfig } from '@ng-bootstrap/ng-bootstrap';
import { Actions, ofActionDispatched, Store } from '@ngxs/store';
import { Observable } from 'rxjs';

import { LogoutAction } from './shared/action/auth.action';
import { GetCartItemsAction } from './shared/action/cart.action';
import { GetCountriesAction } from './shared/action/country.action';
import { GetCurrenciesAction } from './shared/action/currency.action';
import { GetLanguageAction } from './shared/action/language.action';
import { GetSettingOptionAction } from './shared/action/setting.action';
import { GetStatesAction } from './shared/action/state.action';
import { GetThemeOptionAction } from './shared/action/theme-option.action';
import { GetThemesAction } from './shared/action/theme.action';
import { IAnalytics, IValues } from './shared/interface/setting.interface';
import { IOption } from './shared/interface/theme-option.interface';
import { LocationService } from './shared/services/location.service';
import { SeoService } from './shared/services/seo.service';
import { SettingState } from './shared/state/setting.state';
import { ThemeOptionState } from './shared/state/theme-option.state';

@Component({
  selector: 'app-root',
  imports: [RouterOutlet],
  templateUrl: './app.html',
  styleUrl: './app.scss',
})
export class App {
  public meta = inject(Meta);
  public seoService = inject(SeoService);
  public config = inject(NgbRatingConfig);
  private actions = inject(Actions);
  private router = inject(Router);
  private store = inject(Store);
  private locationService = inject(LocationService);

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

  public favIcon: HTMLLinkElement | null;
  public isTabInFocus = true;

  constructor(@Inject(DOCUMENT) document: Document) {
    this.config.max = 5;
    this.config.readonly = true;

    this.store.dispatch(new GetCountriesAction());
    this.store.dispatch(new GetStatesAction());
    this.store.dispatch(new GetCartItemsAction());
    this.store.dispatch(new GetSettingOptionAction());
    this.store.dispatch(new GetThemeOptionAction());
    this.store.dispatch(new GetCurrenciesAction({ status: 1 }));
    this.store.dispatch(new GetThemesAction());
    this.store.dispatch(new GetLanguageAction());

    this.themeOption$.subscribe(theme => {
      if (theme?.general?.mode === 'dark') {
        document
          .getElementsByTagName('html')[0]
          .classList.add(theme?.general && theme?.general?.mode);
      } else {
        document.getElementsByTagName('html')[0].classList.remove('dark');
      }

      // Set Direction
      if (
        theme?.general?.language_direction === 'rtl' ||
        this.store.selectSnapshot(state => state.language && state.language.defaultLanguage.is_rtl)
      ) {
        document.getElementsByTagName('html')[0].setAttribute('dir', 'rtl');
        document.body.classList.add('rtl');
      } else {
        document.getElementsByTagName('html')[0].removeAttribute('dir');
        document.body.classList.remove('rtl');
      }

      // Set Favicon
      this.favIcon = document.querySelector('#appIcon');
      this.favIcon!.href = theme?.logo?.favicon_icon?.original_url;
    });

    this.setting$.subscribe(option => {
      if (option) {
        this.locationService.googleMapApiKey = option.general.google_map_api_key;
        void this.locationService.loadGoogleMapApi();
      }
      if (option?.analytics) {
        if (option?.analytics?.google_analytics && option?.analytics?.google_analytics.status) {
          this.loadScript(option?.analytics);
        }
      }
    });

    // }

    this.actions.pipe(ofActionDispatched(LogoutAction)).subscribe(() => {
      void this.router.navigate(['/auth/login']);
    });
  }

  loadScript(val: IAnalytics): void {
    if (val.google_analytics.status) {
      const script = document.createElement('script');
      script.src = `https://www.googletagmanager.com/gtag/js?id=${val.google_analytics.measurement_id}`;
      document.head.appendChild(script);

      const configScript = document.createElement('script');
      configScript.innerHTML = `
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());
        gtag('config', '${val.google_analytics.measurement_id}');
      `;
      document.head.appendChild(configScript);
    }

    if (val.facebook_pixel.status) {
      const script = document.createElement('script');
      script.src = `https://www.facebook.com/tr?id=${val.facebook_pixel.pixel_id}`;
      document.head.appendChild(script);

      const configScript = document.createElement('script');
      configScript.innerHTML = `
      !function(f,b,e,v,n,t,s)
      {if(f.fbq)return;n=f.fbq=function(){n.callMethod?
      n.callMethod.apply(n,arguments):n.queue.push(arguments)};
      if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
      n.queue=[];t=b.createElement(e);t.async=!0;
      t.src=v;s=b.getElementsByTagName(e)[0];
      s.parentNode.insertBefore(t,s)}(window, document,'script',
      'https://connect.facebook.net/en_US/fbevents.js');
      fbq('init', '${val.facebook_pixel.pixel_id}');
      fbq('track', 'PageView');
      `;
      document.head.appendChild(configScript);
    }
  }
}
