import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Store } from '@ngrx/store';
import { StateInterface } from '../reducers';
import { BehaviorSubject, Observable } from 'rxjs';

interface TranslationData {
  locale: string;
  translations: { [key: string]: string };
}

@Injectable({
  providedIn: 'root'
})
export class TranslationService {
  private translations: { [key: string]: string } = {};
  private currentLang: string = 'fr_FR';
  private translationsLoaded = new BehaviorSubject<boolean>(false);

  constructor(
    private http: HttpClient,
    private store: Store<StateInterface>
  ) {
    // Subscribe to language changes in the store
    this.store.select(state => state.app.lang)
      .subscribe(lang => {
        if (lang !== this.currentLang) {
          this.currentLang = lang;
          this.loadTranslations(lang);
        }
      });

    // Load initial translations
    this.loadTranslations(this.currentLang);
  }

  /**
   * Load translations for the specified language
   * @param lang Language code (e.g., 'fr_FR', 'en_US')
   */
  private loadTranslations(lang: string): void {
    // Convert lang format from 'fr_FR' to 'fr-FR' for file naming
    const langFile = lang.replace('_', '-');

    // Try multiple paths to find the translation file
    this.tryLoadTranslationFromPath(`./locale/${langFile}.json`, lang)
      .catch(() => this.tryLoadTranslationFromPath(`/locale/${langFile}.json`, lang))
      .catch(() => this.tryLoadTranslationFromPath(`assets/locale/${langFile}.json`, lang))
      .catch(() => this.tryLoadTranslationFromPath(`${langFile}.json`, lang))
      .catch((err) => {
        console.error(`Failed to load translations for ${lang} from all paths:`, err);
        // If loading fails, try to load default language (fr_FR)
        if (lang !== 'fr_FR') {
          return this.loadTranslations('fr_FR');
        } else {
          // If default language fails, set an empty translations object
          this.translations = {};
          this.translationsLoaded.next(true);
          return Promise.resolve();
        }
      });
  }

  private tryLoadTranslationFromPath(path: string, lang: string): Promise<void> {
    console.log(`Trying to load translation from: ${path}`);
    return new Promise<void>((resolve, reject) => {
      this.http.get<TranslationData>(path)
        .subscribe({
          next: (data) => {
            console.log(`Successfully loaded translation from: ${path}`);
            this.translations = data.translations;
            this.translationsLoaded.next(true);
            resolve();
          },
          error: (err) => {
            console.error(`Failed to load translation from: ${path}`, err);
            reject(err);
          }
        });
    });
  }

  /**
   * Get a translated string for the given key
   * @param key Translation key
   * @param defaultValue Optional default value if translation is not found
   * @returns Translated string or default value or key if not found
   */
  translate(key: string, defaultValue?: string): string {
    if (this.translations[key]) {
      return this.translations[key];
    }
    return defaultValue || key;
  }

  /**
   * Check if translations are loaded
   * @returns Observable that emits true when translations are loaded
   */
  isLoaded(): Observable<boolean> {
    return this.translationsLoaded.asObservable();
  }

  /**
   * Get the current language
   * @returns Current language code
   */
  getCurrentLang(): string {
    return this.currentLang;
  }
}
