import { NgFor, NgIf } from '@angular/common';
import { Component, OnInit } from '@angular/core';
import { api } from '@enums/api.enum';
import { BlockedUser, CommonResponse } from '@interfaces/common';
import { IonicModule } from '@ionic/angular';
import { AlertService } from '@services/alert.service';
import { HttpRequestService } from '@services/http-request.service';
import { UtilityService } from '@services/utility.service';

@Component({
  selector: 'app-blocked-users',
  templateUrl: './blocked-users.page.html',
  styleUrls: ['./blocked-users.page.scss'],
  standalone: true,
  imports: [IonicModule, NgIf, NgFor]
})
export class BlockedUsersPage implements OnInit {
  users: Array<BlockedUser> = [];
  page = Number(1);
  lastPage = Number(0);
  loader = Boolean(false);

  constructor(
    private httpRequestService: HttpRequestService,
    private utilityService: UtilityService,
    private alert: AlertService
  ) { }

  ngOnInit() {
    this.fetchBlockedUsers();
  }

  loadData(event: any) {
    if (this.page === this.lastPage) {
      event.target.disabled = true;
      return;
    }
    this.page++;
    this.fetchBlockedUsers().then(() => {
      event.target.complete();
    });
  }

  fetchBlockedUsers() {
    if (this.page === 1) {
      this.loader = true;
    }
    return this.httpRequestService.get(api.getBlockedUsers, {
      page: this.page
    }).then((res: CommonResponse) => {
      this.users = this.page === 1 ? res.data.data : this.users.concat(res.data.data);
      this.lastPage = res.data.last_page;
    }).finally(() => {
      this.loader = false;
    });
  }

  async unblock(id: number) {
    const isYes = await this.utilityService.presentConfirm(
      'Are you sure you want to unblock this user?'
    );
    if (isYes) {
      this.alert.showLoader();
      this.httpRequestService.post(api.blockThisUser, {
        id,
        status: 0
      })
        .then((res: CommonResponse) => {
          this.users.splice(this.users.findIndex(i => i.user_id === id), 1);
          this.alert.showToaster(res.message);
        }).finally(() => {
          this.alert.hideLoader();
        });
    }
  }

}
