import { Component, computed, DestroyRef, inject, OnInit, signal } from '@angular/core';
import { Comic } from '../comic.model';
import { ComicService } from '../comic-comics/comic.service';
import { ComicComicComponent } from '../comic-comic/comic-comic.component';

@Component({
  selector: 'app-comic-comics-list',
  imports: [ComicComicComponent],
  templateUrl: './comic-comics-list.component.html',
  styleUrl: './comic-comics-list.component.css',
})
export class ComicComicsListComponent implements OnInit {
  comicsFetched = signal<Comic[] | undefined>(undefined);
  searchQuery = signal<string>('');
  comics = computed(() => {
    const sq = this.searchQuery();
    return this.comicsFetched()?.filter(c => c.title.toLowerCase().includes(sq.toLowerCase()));
  });
  isFetching = signal(false);
  error = signal('');
  private comicsService = inject(ComicService);
  private destroyRef = inject(DestroyRef);

  ngOnInit() {
    this.isFetching.set(true);
    const subscription = this.comicsService.loadComics().subscribe({
      next: (comics) => {
        this.comicsFetched.set(comics);
      },
      error: (error: Error) => {
        this.error.set(error.message);
      },
      complete: () => {
        this.isFetching.set(false);
      },
    });

    this.destroyRef.onDestroy(() => {
      subscription.unsubscribe();
    });
  }

  search(query: string) {
    this.searchQuery.set(query);
  }
}
