import { Injectable, signal } from '@angular/core';
import { Router } from '@angular/router';
import { LocalStorageService } from '../core/storage/local-storage.service';
import { CurrencyRatesService } from './currency-rates.service';

export interface Language {
  code: string;
  name: string;
  flag: string;
  flagSvg: string;
  enabled: boolean;
}

export interface Currency {
  code: string;
  symbol: string;
  name: string;
}

@Injectable({
  providedIn: 'root'
})
export class LanguageService {
  private currentLanguageSignal = signal<string>('ru');
  private currentCurrencySignal = signal<string>('RUB');

  languages: Language[] = [
    { code: 'ru', name: 'Русский', flag: '🇷🇺', flagSvg: '/flags/ru.svg', enabled: true },
    { code: 'en', name: 'English', flag: '🇬🇧', flagSvg: '/flags/en.svg', enabled: true },
    { code: 'hy', name: 'Հայերեն', flag: '🇦🇲', flagSvg: '/flags/arm.svg', enabled: true }
  ];

  currencies: Currency[] = [
    { code: 'RUB', symbol: '₽', name: 'Рубль' },
    { code: 'USD', symbol: '$', name: 'Dollar' },
    { code: 'EUR', symbol: '€', name: 'Euro' },
    { code: 'AMD', symbol: '֏', name: 'Դրամ' },
  ];

  currentLanguage = this.currentLanguageSignal.asReadonly();
  currentCurrency = this.currentCurrencySignal.asReadonly();

  constructor(
    private router: Router,
    private readonly storage: LocalStorageService,
    private readonly currencyRates: CurrencyRatesService,
  ) {
    // Load saved language from localStorage
    const savedLang = this.storage.getItem('selectedLanguage');
    if (savedLang && this.languages.find(l => l.code === savedLang && l.enabled)) {
      this.currentLanguageSignal.set(savedLang);
    }

    const savedCurrency = this.storage.getItem('selectedCurrency');
    if (savedCurrency && this.currencies.find(c => c.code === savedCurrency)) {
      this.currentCurrencySignal.set(savedCurrency);
    }
  }

  setLanguage(langCode: string): void {
    const lang = this.languages.find(l => l.code === langCode);
    if (lang && lang.enabled) {
      this.currentLanguageSignal.set(langCode);
      this.storage.setItem('selectedLanguage', langCode);
    }
  }

  setCurrency(code: string): void {
    const currency = this.currencies.find(c => c.code === code);
    if (currency) {
      this.currentCurrencySignal.set(code);
      this.storage.setItem('selectedCurrency', code);
      // PHASE-1-MONEY-FX-PAYMENTS-CONTRACT.md §3: fetch a fresh quote on
      // switch rather than waiting for the next getRate() call to notice the
      // cached one is stale - the displayed price should update as soon as
      // the switch happens, not one render behind it.
      void this.currencyRates.ensureFreshQuote(code);
    }
  }

  getCurrentCurrency(): Currency | undefined {
    return this.currencies.find(c => c.code === this.currentCurrencySignal());
  }

  /** Change language and navigate to the same page with the new prefix */
  switchLanguage(langCode: string): void {
    const lang = this.languages.find(l => l.code === langCode);
    if (!lang?.enabled) return;

    const currentUrl = this.router.url;
    const currentLang = this.currentLanguageSignal();
    const newUrl = currentUrl.replace(new RegExp(`^/${currentLang}`), `/${langCode}`);

    this.setLanguage(langCode);
    this.router.navigateByUrl(newUrl);
  }

  getCurrentLanguage(): Language | undefined {
    return this.languages.find(l => l.code === this.currentLanguageSignal());
  }
}
