import { NgFor, NgIf } from '@angular/common';
import { Component, OnInit } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { Router } from '@angular/router';
import { api } from '@enums/api.enum';
import { IonicModule, NavController } from '@ionic/angular';
import { AlertService } from '@services/alert.service';
import { HttpRequestService } from '@services/http-request.service';
import { StateManagementService } from '@services/state-management.service';

@Component({
  selector: 'app-select-sangh',
  templateUrl: './select-sangh.page.html',
  styleUrls: ['./select-sangh.page.scss'],
  standalone: true,
  imports: [IonicModule, FormsModule, NgFor, NgIf]
})
export class SelectSanghPage implements OnInit {
  sanghList = [];
  selectedSangh = [];
  checkAll = false;

  constructor(
    private navCtrl: NavController,
    private router: Router,
    private alert: AlertService,
    private stateManagementService: StateManagementService,
    private httpRequestService: HttpRequestService
  ) { }

  ngOnInit() {
    if (this.router.getCurrentNavigation().extras.state?.selectedSangh) {
      this.selectedSangh = this.router.getCurrentNavigation().extras.state.selectedSangh;
    }
    if (this.stateManagementService.userSanghList.length > 0) {
      this.prepareSanghList(this.stateManagementService.userSanghList);
    } else {
      this.getSanghList();
    }
  }

  prepareSanghList(data) {
    this.sanghList = data.map(i => {
      i.checked = this.selectedSangh.includes(i.id);
      return i;
    });
  }

  getSanghList() {
    this.httpRequestService.get(api.associatedSanghList).then((res: any) => {
      this.stateManagementService.userSanghList = res.data;
      this.prepareSanghList(res.data);
    });
  }

  onCheckAll() {
    this.sanghList.forEach(i => {
      i.checked = this.checkAll;
    });
  }

  onAdd() {
    this.selectedSangh = this.sanghList.filter(i => i.checked).map(i => i.id);
    if (!this.selectedSangh.length) {
      this.alert.showToasterError('Please select sangh.');
      return;
    }
    this.stateManagementService.postSelectedSanghSubject.next(this.selectedSangh);
    this.navCtrl.back();
  }

}
