import { NgFor, NgIf } from '@angular/common';
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { ActivatedRoute } from '@angular/router';
import { api } from '@enums/api.enum';
import { Roots } from '@enums/root.enum';
import { IonicModule, NavController } 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-add-committee-member',
  templateUrl: './add-committee-member.page.html',
  styleUrls: ['./add-committee-member.page.scss'],
  standalone: true,
  imports: [IonicModule, FormsModule, NgFor, NgIf]
})
export class AddCommitteeMemberPage {
  sanghId: string;
  userList = [];
  searchValue: string;
  prevValue: string;
  pageNumber = 1;
  totalPage = 1;
  postTypeId: any;
  userData: any;
  constructor(
    private cRoute: ActivatedRoute,
    private navCtrl: NavController,
    private httpRequestService: HttpRequestService,
    private alert: AlertService,
    private utilityService: UtilityService
  ) { }

  ionViewWillEnter() {
    this.sanghId = this.cRoute.snapshot.paramMap.get('id');
    this.getUserList(false, '');
  }

  searchSangh() {
    const isSameStr = this.utilityService.isSameStr(this.searchValue, this.prevValue);
    this.prevValue = this.searchValue;
    if (!isSameStr) {
      this.userList = [];
      this.pageNumber = 1;
      this.totalPage = 1;
      this.getUserList(false, '');
    }
  }

  getUserList(isFirstLoad, event) {
    if (this.pageNumber <= this.totalPage) {
      const params = {
        page: this.pageNumber,
        limit: 15,
        name: this.searchValue ? this.searchValue.trim() : '',
        sangh_id: this.sanghId,
      };
      this.httpRequestService.post(api.memberListForAddInSangh, params).then((res: any) => {
        this.totalPage = res.data.last_page;
        this.userList = res.data.data;
        if (isFirstLoad) {
          event.target.complete();
        }
        this.pageNumber++;
      }).catch((err) => {
        this.alert.showToasterError(err.error);
      });
    } else {
      event.target.complete();
    }
  }

  onTypeChange(type) {
    this.userData = type;
  }

  goToAddRole() {
    const navOption = {
      state: {
        userValue: this.userData,
        id: this.cRoute.snapshot.paramMap.get('id')
      },
    };
    this.navCtrl.navigateForward(Roots.page + '/' + Roots.sanghRoleSelect, navOption);
  }

}
