import {
  Component,
  EventEmitter,
  Input,
  OnChanges,
  Output,
  SimpleChanges,
} from '@angular/core';
import { RecipeTag } from 'src/app/shared/interfaces/services/api-fit/response/recipe.interface';
import { ApiFitService } from 'src/app/shared/services/api-fit/api-fit.service';

@Component({
  selector: 'app-add-tag',
  templateUrl: './add-tag.component.html',
  styleUrls: ['./add-tag.component.scss'],
})
export class AddTagComponent implements OnChanges {
  @Input() isVisible = false;
  @Input() selectedTags: RecipeTag[] = [];

  @Output() isVisibleChange = new EventEmitter<boolean>();
  @Output() selectedTagsChange = new EventEmitter<RecipeTag[]>();
  @Output() onSelectTags = new EventEmitter<RecipeTag[]>();

  searchTerm = '';
  tags: RecipeTag[] = [];

  page = 1;
  totalPages = 1;
  itemsPerPage = 8;

  constructor(private apiFitService: ApiFitService) {}

  ngOnInit() {
    this.searchTags();
  }

  ngOnChanges(changes: SimpleChanges): void {
    if (changes['isVisible']?.currentValue) {
      this.searchTags();
    }
  }

  handleClose() {
    this.isVisibleChange.emit(false);
  }

  searchTags(term?: string) {
    this.tags = [...this.selectedTags];

    this.searchTerm = term ?? '';

    this.apiFitService
      .getRecipesTags({
        search_by_name: this.searchTerm,
        page: this.page,
        items_per_page: this.itemsPerPage,
      })
      .subscribe({
        next: (res) => {
          this.tags = [
            ...this.selectedTags,
            ...res.data.filter(
              (t) => !this.selectedTags.find((tag) => tag.id === t.id),
            ),
          ];

          this.page = res.actualPage;
          this.totalPages = res.totalPages;
        },
        error: () => {
          this.tags = [...this.selectedTags];

          this.page = 1;
          this.totalPages = 1;
        },
      });
  }

  isTagSelected(tag: RecipeTag) {
    return this.selectedTags.some((item) => item.id === tag.id);
  }

  toggleTag(tag: RecipeTag) {
    const index = this.selectedTags.findIndex((item) => item.id === tag.id);

    if (index !== -1) {
      this.selectedTags.splice(index, 1);
    } else {
      this.selectedTags.push(tag);
    }

    this.tags = [...new Set([...this.selectedTags, ...this.tags])];
    this.selectedTagsChange.emit(this.selectedTags);
  }

  handleContinue() {
    this.onSelectTags.emit(this.selectedTags);
    this.isVisibleChange.emit(false);
  }
}
