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

import { Store } from '@ngxs/store';
import { Observable } from 'rxjs';

import { SelectedCurrencyAction } from '../../../../../shared/action/setting.action';
import { ICurrency, ICurrencyModel } from '../../../../../shared/interface/currency.interface';
import { IValues } from '../../../../../shared/interface/setting.interface';
import { CurrencyState } from '../../../../../shared/state/currency.state';
import { SettingState } from '../../../../../shared/state/setting.state';
import { ClickOutsideDirective } from '../../../../directive/out-side-directive';
import { Button } from '../../../widgets/button/button';

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

  setting$: Observable<IValues> = inject(Store).select(SettingState.setting) as Observable<IValues>;
  selectedCurrency$: Observable<ICurrency> = inject(Store).select(
    SettingState.selectedCurrency,
  ) as Observable<ICurrency>;

  public open: boolean = false;
  public selectedCurrency: ICurrency;
  public setting: IValues;

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

  currency$: Observable<ICurrencyModel> = inject(Store).select(
    CurrencyState.currency,
  ) as Observable<ICurrencyModel>;

  constructor() {
    this.selectedCurrency$.subscribe(setting => (this.selectedCurrency = setting));
  }

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

  selectCurrency(currency: ICurrency) {
    this.selectedCurrency = currency;
    this.open = false;
    this.store.dispatch(new SelectedCurrencyAction(currency)).subscribe({
      complete: () => {
        window.location.reload();
      },
    });
  }

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