import { CommonModule } from '@angular/common';
import { Component, inject, input } from '@angular/core';

import { TranslateService } from '@ngx-translate/core';
import { Store } from '@ngxs/store';
import { Observable } from 'rxjs';

import { SetDefaultLanguageAction } from '../../../../action/language.action';
import { ClickOutsideDirective } from '../../../../directive/out-side-directive';
import { ILanguage, ILanguageModel } from '../../../../interface/language.interface';
import { IValues } from '../../../../interface/setting.interface';
import { TranslationLoader } from '../../../../services/translation-loader.service';
import { LanguageState } from '../../../../state/language.state';
import { SettingState } from '../../../../state/setting.state';
import { Button } from '../../../widgets/button/button';

@Component({
  selector: 'app-language',
  imports: [Button, ClickOutsideDirective, CommonModule],
  templateUrl: './language.html',
  styleUrl: './language.scss',
})
export class Language {
  private store = inject(Store);
  private translate = inject(TranslateService);
  private translationLoader = inject(TranslationLoader);

  readonly style = input<string>('basic');

  language$: Observable<ILanguageModel> = inject(Store).select(
    LanguageState.language,
  ) as Observable<ILanguageModel>;
  defaultLanguage$: Observable<ILanguage> = inject(Store).select(
    LanguageState.defaultLanguage,
  ) as Observable<ILanguage>;
  setting$: Observable<IValues> = inject(Store).select(SettingState.setting) as Observable<IValues>;

  public active: boolean = false;

  ngOnInit() {
    this.defaultLanguage$.subscribe(language => {
      if (language) {
        this.translate.use(language.locale);
      }
    });
    this.translationLoader.getTranslation();
  }

  selectLanguage(language: ILanguage) {
    this.active = false;
    this.store.dispatch(new SetDefaultLanguageAction(language));
    this.translate.use(language.locale);
    location.reload();
  }

  openDropDown() {
    this.active = !this.active;
  }

  hideDropdown() {
    this.active = false;
  }
}
