import { NgFor, NgIf } from '@angular/common';
import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { FormControl, FormGroup, FormsModule, ReactiveFormsModule, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { IonicSelectableItemTemplateDirective } from '@components/ionic-selectable/ionic-selectable-item-template.directive';
import { IonicSelectableComponent } from '@components/ionic-selectable/ionic-selectable.component';
import { api } from '@enums/api.enum';
import { Roots } from '@enums/root.enum';
import { IdName, SanghData } from '@interfaces/common';
import { ChaturmasInfoForm } from '@interfaces/form';
import { AlertController, 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';
import { UtilityService } from '@services/utility.service';
@Component({
  selector: 'app-add-chaturmas',
  templateUrl: './add-chaturmas.page.html',
  styleUrls: ['./add-chaturmas.page.scss'],
  standalone: true,
  imports: [IonicModule, FormsModule, ReactiveFormsModule, NgIf, IonicSelectableComponent, NgFor, IonicSelectableItemTemplateDirective]
})
export class AddChaturmasPage implements OnInit {
  @ViewChild('Location') Location: ElementRef;
  @ViewChild('sanghListComponent') sanghListComponent: IonicSelectableComponent;
  chaturmasInfoForm: FormGroup<ChaturmasInfoForm>;
  chaturmasYearList = [];
  sanghList: Array<SanghData> = [];
  santId: string;
  sanghId: string;
  chaturmasId: string;
  dharmaId: string;
  sampradayId: string;
  sanghName: string;
  thanaMemberCount: string;
  chaturmasPlace = '';
  chaturmasYear = '';
  isUpdate = false;
  title = '';
  chaturmasWithLocation = false;
  chaturmasWith = 'sangh';
  pageNumber = 1;
  totalPage = 1;
  thanaList: any[] = [];
  confirmationFlag = false;
  message = `Thank you for submitting Chatumas details.
  GlobalJain admin will verify and confirm within 48 hours.
  Once approved, you will be awarded Karmā points`;
  latitude: string;
  longitude: string;
  selectedSangh: IdName = null;
  sanghPageNumber = 1;
  sanghTotalPages = 1;
  sanghSearchText = '';
  prevValue: string;

  constructor(
    private httpRequestService: HttpRequestService,
    private alert: AlertService,
    private router: Router,
    private navCtrl: NavController,
    private stateManagementService: StateManagementService,
    public alertController: AlertController,
    private utilityService: UtilityService
  ) { }

  async ngOnInit() {
    const state = this.router.getCurrentNavigation().extras?.state;
    if (state) {
      this.santId = state.santId;
      this.dharmaId = state.dharmaId;
      this.sampradayId = state.sampradayId;
      this.chaturmasId = state.chaturmasId;
      this.chaturmasPlace = state.chaturmasPlace;
      this.chaturmasYear = state.chaturmasYear;
      this.isUpdate = state.isUpdate;
      this.sanghId = state.sanghId;
      this.sanghName = state.sanghName;
      this.thanaMemberCount = state.thanaMemberCount;
      this.setSanghField();
    }
    this.title = this.isUpdate ? 'Update' : 'Add';
    if (this.stateManagementService.chaturmasYear.length > 0) {
      this.chaturmasYearList = this.stateManagementService.chaturmasYear;
    } else {
      this.getChaturmasYear();
    }
    this.chaturmasInfoForm = new FormGroup<ChaturmasInfoForm>({
      chaturmasPlace: new FormControl(this.chaturmasPlace),
      sanghId: new FormControl(this.sanghId),
      sanghName: new FormControl(this.sanghName),
      chaturmasYear: new FormControl(this.chaturmasYear, Validators.required)
    });
    this.setValidation(this.chaturmasWithLocation);
    this.getThanaList(false, '');
  }

  setSanghField() {
    if (this.sanghId) {
      this.selectedSangh = {
        id: +this.sanghId,
        name: this.sanghName,
      };
      this.chaturmasInfoForm.controls.sanghName.setValue(this.sanghName);
      this.chaturmasInfoForm.controls.sanghId.setValue(this.sanghId);
    }
  }

  onRadioChange(event) {
    this.chaturmasWithLocation = (event?.detail?.value === 'location') ? true : false;
    this.setValidation(this.chaturmasWithLocation);
  }

  setValidation(chaturmasWithLocation) {
    this.chaturmasInfoForm.controls.chaturmasPlace.setValidators(!chaturmasWithLocation ? null : [Validators.required]);
    this.chaturmasInfoForm.controls.sanghId.setValidators(chaturmasWithLocation ? null : [Validators.required]);
    this.chaturmasInfoForm.controls.sanghName.setValidators(chaturmasWithLocation ? null : [Validators.required]);
    this.chaturmasInfoForm.controls.chaturmasPlace.updateValueAndValidity();
    this.chaturmasInfoForm.controls.sanghId.updateValueAndValidity();
    this.chaturmasInfoForm.controls.sanghName.updateValueAndValidity();
  }

  getChaturmasYear() {
    this.httpRequestService.get(api.chaturmasYear).then((res: any) => {
      this.chaturmasYearList = res.data;
      this.stateManagementService.chaturmasYear = res.data;
    });
  }

  searchSangh(event: { component: IonicSelectableComponent; text: string }) {
    const isSameStr = this.utilityService.isSameStr(event.text, this.prevValue);
    this.prevValue = event.text;
    if (!isSameStr) {
      this.sanghPageNumber = 1;
      this.sanghList = [];
      this.sanghSearchText = event.text;
      event.component.showLoading();
      this.getSanghList().then(() => {
        event.component.hideLoading();
      });
    }
  }

  getSanghList() {
    return this.httpRequestService.get(api.sanghSearchList, {
      name: this.sanghSearchText,
      page: this.sanghPageNumber,
      limit: 15
    }).then((res: any) => {
      this.sanghList.push(...res.data.data);
      this.sanghTotalPages = res.data.last_page;
    });
  }

  addSangh(sangh) {
    this.sanghName = sangh.value.name;
    this.sanghId = sangh.value.id;
    this.setSanghField();
    this.sanghList = [];
    this.sanghListComponent.searchText = '';
    this.sanghSearchText = '';
    this.sanghPageNumber = 1;
    this.getSanghList();

  }

  submitChaturmas() {
    if (!this.isUpdate) {
      this.addChaturmas();
    } else {
      this.updateChaturmas();
    }
  }

  addChaturmas() {
    this.presentAlertPrompt('add');
  }

  updateChaturmas() {
    this.presentAlertPrompt('update');
  }

  initAutocompletePlace(): void {
    this.utilityService.createAutocomplete(this.Location.nativeElement).subscribe((details) => {
      this.chaturmasInfoForm.controls.chaturmasPlace.setValue(this.Location.nativeElement.value);
      this.latitude = details.geometry.location.lat();
      this.longitude = details.geometry.location.lng();
    });
  }

  removeLatAndLong() {
    this.latitude = '';
    this.longitude = '';
  }

  moveToChaturmas() {
    this.navCtrl.navigateBack(Roots.page + '/' + Roots.chaturmasInfo.replace(':santId', this.santId));
  }

  async ionViewWillEnter() {
    await this.getSanghList();
  }

  ionViewWillLeave() {
    this.chaturmasInfoForm.reset();
  }

  getThanaList(isFirstLoad, event) {
    if (this.pageNumber <= this.totalPage) {
      this.httpRequestService.post(api.santThanaList, {
        sant_id: Number(this.santId),
        page: this.pageNumber
      }).then((res: any) => {
        this.totalPage = res.data.last_page;
        this.thanaList.push(...res.data.data);
        if (isFirstLoad) { event.target.complete(); }
        this.pageNumber++;
      });
    } else {
      event.target.complete();
    }
  }

  async presentAlert() {
    const message = +this.thanaMemberCount > 0 ?
      `Thank you for submitting chaturmas details.
     GlobalJain admin will verify and confirm within 48 hours.
      Once approved, you will be awarded karmā points.
       <span>Chaturmas will be applicable to all Thana(s)</span>` :
      `Thank you for submitting chaturmas details.
         GlobalJain admin will verify and confirm within 48 hours.
          Once approved, you will be awarded karmā points`;
    const alert = await this.alertController.create({
      cssClass: 'chaturmas-approval',
      backdropDismiss: false,
      message,
      buttons: [{
        text: 'Ok',
        handler: () => {
          this.moveToChaturmas();
        }
      }]
    });
    await alert.present();
  }

  async presentAlertPrompt(type: string) {
    if (this.chaturmasInfoForm.invalid || !this.confirmationFlag) {
      this.chaturmasInfoForm.markAllAsTouched();
      return;
    }
    const isYes = await this.utilityService.presentConfirm(
      'Are you sure that all information is correct? ' +
      'Chaturmas will be applicable to all Thana\'s.'
    );
    if (isYes) {
      if (type === 'add') {
        this.httpRequestService.post(api.addChaturmas, {
          sant_id: Number(this.santId),
          year: this.chaturmasInfoForm.value.chaturmasYear,
          ...this.chaturmasWithLocation && {
            place: this.chaturmasInfoForm.value.chaturmasPlace,
            latitude: this.latitude,
            longitude: this.longitude,
          },
          ...!this.chaturmasWithLocation && { sangh_id: this.chaturmasInfoForm.value.sanghId },
        })
          .then(() => {
            this.presentAlert();
          }).catch((err) => {
            this.alert.showToasterError(err.error.error);
          });
      } else if (type === 'update') {
        this.httpRequestService.post(api.addChaturmas + '/' + this.chaturmasId, {
          year: this.chaturmasInfoForm.value.chaturmasYear,
          ...this.chaturmasWithLocation && {
            place: this.chaturmasInfoForm.value.chaturmasPlace,
            latitude: this.latitude,
            longitude: this.longitude,
          },
          ...!this.chaturmasWithLocation && { sangh_id: this.chaturmasInfoForm.value.sanghId },
        })
          .then(() => {
            this.presentAlert();
          });
      }
    }
  }

  getMoreSangh(event: { component: IonicSelectableComponent; text: string }) {
    if (this.sanghPageNumber >= this.sanghTotalPages) {
      event.component.disableInfiniteScroll();
      return;
    }
    this.sanghPageNumber++;
    this.getSanghList().then(() => {
      event.component.endInfiniteScroll();
    });
  }

}
