import { Component, inject, Input, signal } from '@angular/core';
import { Button } from 'primeng/button';
import { finalize, Observable } from 'rxjs';
import { PosGoodFavoriteService } from '../services/favorite.service';
import { PosLandingStore } from '../store/main.store';

@Component({
  selector: 'pos-good-favorite-cta',
  templateUrl: 'favorite-CTA.component.html',
  imports: [Button],
})
export class FavoriteCTAComponent {
  private readonly favoriteService = inject(PosGoodFavoriteService);
  private readonly store = inject(PosLandingStore);

  @Input({ required: true }) id!: string;
  @Input({ required: true }) isFavorite!: boolean;
  @Input() size?: 'small' | 'large';

  loading = signal(false);

  toggleFavorite(goodId: string, currentState: boolean) {
    if (this.loading()) return;
    if (currentState) {
      this.detachFavorite(goodId);
    } else {
      this.attachFavorite(goodId);
    }
  }

  attachFavorite(goodId: string) {
    this.handleFavoriteRequest(this.favoriteService.attach(goodId), goodId, true);
  }

  detachFavorite(goodId: string) {
    this.handleFavoriteRequest(this.favoriteService.detach(goodId), goodId, false);
  }

  private handleFavoriteRequest(
    request$: Observable<unknown>,
    goodId: string,
    isFavorite: boolean,
  ) {
    this.loading.set(true);
    request$
      .pipe(
        finalize(() => {
          this.loading.set(false);
        }),
      )
      .subscribe(() => {
        this.store.toggleGoodFavorite(goodId, isFavorite);
      });
  }
}
