import { Component } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Store } from '@ngrx/store';
import { distinctUntilChanged } from 'rxjs';
import { UserStore } from 'src/app/core/interfaces/user.interface';
import { AuthService } from 'src/app/core/services/auth/auth.service';
import { UserDispatchers } from 'src/app/core/stores/index.dispatchers';
import { RecipeFilters } from 'src/app/shared/interfaces/services/api-fit/request/recipe.interface';
import { Recipe } 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-profile',
  templateUrl: './profile.component.html',
  styleUrls: ['./profile.component.scss'],
})
export class ProfileComponent {
  confirmLogoutIsOpen = false;
  confirmedLogout = false;

  isPersonalProfile = false;
  user!: UserStore;
  recipes: Recipe[] = [];

  totalPages = 0;

  filter: RecipeFilters = {
    page: 1,
    items_per_page: 20,
    self: false,
    from_user_id: 0,
    from_username: '',
    liked_only: false,
    tags_ids: [],
    min_calorie_content_per_portion: 0,
    max_calorie_content_per_portion: 0,
    servings: 0,
    ingredients_ids: [],
    order_by: 'id.desc',
    search_by_name: '',
  };

  filtersCounter = '';
  isModalFiltersOpen = false;

  constructor(
    private route: ActivatedRoute,
    private apiService: ApiFitService,
    private store: Store<{ user: UserStore }>,
    private router: Router,
    private authService: AuthService,
    private userDispatchers: UserDispatchers,
  ) {}

  ngOnInit() {
    this.setFilterFromQuery();

    this.route.params.subscribe({
      next: (params) => {
        this.store.select('user').subscribe({
          next: (user) => {
            this.user = user;

            if (params['username']) {
              this.apiService.getUserByUsername(params['username']).subscribe({
                next: (res) => {
                  this.isPersonalProfile = this.user.id === res.data.id;

                  this.user = res.data;
                  this.fetchRecipes();
                },
                error: () => this.router.navigate(['/app/profile']),
              });

              return;
            }

            this.isPersonalProfile = true;
            this.fetchRecipes();
          },
        });
      },
    });
  }

  fetchRecipes() {
    this.updateQueryParamsFromFilter();
    this.countFilters();

    this.apiService
      .getAllRecipes({
        ...this.filter,
        from_username: this.user.username,
      })
      .pipe(distinctUntilChanged())
      .subscribe({
        next: (res) => {
          this.totalPages = res.totalPages ?? 0;
          this.filter.page = res.actualPage ?? 1;
          this.recipes = res.data;
        },
        error: () => (this.recipes = []),
      });
  }

  setFilterFromQuery() {
    this.route.queryParams.subscribe({
      next: (p) => {
        this.filter = {
          ...this.filter,
          ...p,
        };
      },
    });
  }

  openModalFilters() {
    this.isModalFiltersOpen = true;
  }

  updateQueryParamsFromFilter() {
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    const validParams = Object.entries(this.filter).filter(([_, value]) => {
      if (Array.isArray(value)) {
        return !!value.length;
      }

      return !!value;
    });

    const filterParams = Object.fromEntries(validParams);

    this.router.navigate([], {
      relativeTo: this.route,
      queryParams: null,
    });

    setTimeout(() => {
      this.router.navigate([], {
        relativeTo: this.route,
        queryParams: filterParams,
      });
    }, 100);
  }

  countFilters() {
    const ignoreKeys = [
      'page',
      'search_by_name',
      'liked_only',
      'self',
      'items_per_page',
    ];
    const ignoreValues = [0, false, '', 'id.desc'];

    this.route.queryParams.subscribe({
      next: (p) => {
        const keysParams = Object.keys(p);

        const validValues = keysParams.filter((k) => {
          return !ignoreKeys.includes(k) && !ignoreValues.includes(p[k]);
        });

        if (validValues.length) {
          this.filtersCounter = `(${validValues.length})`;
        } else {
          this.filtersCounter = '';
        }
      },
    });
  }

  openLogoutDialog(ev: Event) {
    ev.preventDefault();

    this.confirmLogoutIsOpen = true;
  }

  onConfirmLogout() {
    this.authService.clearAuthorizationToken();
    this.userDispatchers.clearUser();

    this.confirmedLogout = true;
  }

  onCloseAlert() {
    this.router.navigate(['/app/auth/login']);
  }
}
