import { NgFor, NgIf } from '@angular/common';
import { Component, OnInit } from '@angular/core';
import { Router } 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-thana',
  templateUrl: './add-thana.page.html',
  styleUrls: ['./add-thana.page.scss'],
  standalone: true,
  imports: [IonicModule, NgFor, NgIf]
})
export class AddThanaPage implements OnInit {
  santList = [];
  pageNumber = 1;
  totalPage = 1;
  searchValue: string;
  prevValue: string;
  santId = '1';
  santIdArray = [];
  totalCount: number;

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

  ngOnInit() {
    this.santId = this.router.getCurrentNavigation().extras.state?.santId;
    this.getSantList(false, '');
  }

  addSant(index) {
    this.santIdArray.push(this.santList[index].id);
    this.santList[index].isAdded = !this.santList[index].isAdded;
  }

  removeSant(index) {
    const i = this.santIdArray.indexOf(this.santList[index].id);
    if (i > -1) {
      this.santIdArray.splice(i, 1);
    }
    this.santList[index].isAdded = !this.santList[index].isAdded;
  }

  searchSant($event) {
    this.searchValue = $event.detail.value;
    const isSameStr = this.utilityService.isSameStr(this.searchValue, this.prevValue);
    this.prevValue = this.searchValue;
    if (!isSameStr) {
      this.santList = [];
      this.pageNumber = 1;
      this.totalPage = 1;
      this.getSantList(false, '');
    }
  }

  loadData($event) {
    this.getSantList(true, $event);
  }

  getSantList(isFirstLoad, event) {
    if (this.pageNumber <= this.totalPage) {
      const params = {
        page: this.pageNumber,
        limit: 15,
        sant_id: this.santId,
        name: this.searchValue?.trim(),
      };
      this.httpRequestService.post(api.thanaSantList, params).then((res: any) => {
        this.totalPage = res.data.last_page;
        this.totalCount = res.data.total;
        this.santList.push(...res.data.data.map(d => {
          d.isAdded = !this.santIdArray.includes(d.id);
          return d;
        }));
        if (isFirstLoad) {
          event.target.complete();
        }
        this.pageNumber++;
      }).catch((err) => {
        this.alert.showToasterError(err.error);
      });
    } else {
      event.target.complete();
    }
  }

  addThana() {
    const formData = new FormData();
    formData.append('sant_id', this.santId);
    for (const [index, santId] of this.santIdArray.entries()) {
      formData.append(`thana_sant_id[${index}]`, santId);
    }
    this.httpRequestService.post(api.addThana, formData).then((res: any) => {
      this.alert.showToaster(res.message);
      this.navCtrl.navigateBack(Roots.page + '/' + Roots.thanaList.replace(':santId', this.santId));
    }).catch((err) => {
      this.alert.showToasterError(err.error);
    });
  }

}
