import { NgIf } from '@angular/common';
import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { api } from '@enums/api.enum';
import { Roots } from '@enums/root.enum';
import { ActionSheetController, IonicModule, NavController } from '@ionic/angular';
import { SafeUrlPipe } from '@pipes/safe-url.pipe';
import { AlertService } from '@services/alert.service';
import { CameraGalleryService } from '@services/camera-gallery.service';
import { HttpRequestService } from '@services/http-request.service';
import { SantInfoService } from '@services/sant-info.service';
import { UtilityService } from '@services/utility.service';

@Component({
  selector: 'app-sangh-profile-image',
  templateUrl: './sangh-profile-image.page.html',
  styleUrls: ['./sangh-profile-image.page.scss'],
  standalone: true,
  imports: [IonicModule, NgIf, SafeUrlPipe]
})
export class SanghProfileImagePage implements OnInit {
  @ViewChild('fileInput', { static: true }) fileInput: ElementRef;
  photo: any;
  constructor(
    private navCtrl: NavController,
    public santService: SantInfoService,
    public actionSheetCtrl: ActionSheetController,
    private alert: AlertService,
    private httpRequestService: HttpRequestService,
    private utilityService: UtilityService,
    private cameraGalleryService: CameraGalleryService
  ) { }

  ngOnInit() {
    if (this.santService.sanghProfileImage.controls.avatar.value instanceof Blob) {
      const reader = new FileReader();
      reader.onload = () => {
        this.photo = reader.result.toString();
      };
      reader.readAsDataURL(this.santService.sanghProfileImage.controls.avatar.value);
    } else if (typeof (this.santService.sanghProfileImage.controls.avatar.value) === 'string') {
      this.photo = this.santService.sanghProfileImage.controls.avatar.value;
    }
  }

  selectProfileImage() {
    this.cameraGalleryService.selectImage(512, 512, true).then((imageData: { imgString: string; itemImage: Blob }) => {
      if (imageData) {
        this.photo = imageData.imgString;
        this.santService.sanghProfileImage.controls.avatar.setValue(imageData.itemImage);
      }
    });
  }

  addSangh(formdata) {
    this.presentAlertPrompt(formdata);
  }

  moveToBack() {
    this.navCtrl.navigateForward(Roots.page + '/' + Roots.sanghAddress);
  }

  goToInviteMembers() {
    const formdata = new FormData();
    for (const [, formValue] of Object.entries(this.santService.sanghInformationForm.value)) {
      for (const [key, value] of Object.entries(formValue)) {
        if (value !== null && value !== undefined && value !== '') {
          if ((typeof (value) === 'string' || value instanceof Blob)) {
            formdata.append(key, value);
          } else if ((typeof (value) === 'number' || value instanceof Array)) {
            formdata.append(key, value.toString());
          }
        }
      }
    }

    if (formdata.has('bank_qr_code_url')) {
      formdata.delete('bank_qr_code_url');
    }

    if (this.santService.sanghInformationForm.value.sanghInfoForm.sampraday_id) {
      formdata.append('sampraday_id', this.santService.sanghInformationForm.value.sanghInfoForm.sampraday_id.id);
    }
    if (this.santService.sanghInformationForm.value.sanghInfoForm.mulnayak_bhagwan_name) {
      formdata.append('mulnayak_bhagwan_name', this.santService.sanghInformationForm.value.sanghInfoForm.mulnayak_bhagwan_name.id);
    }
    if (!this.photo) {
      this.alert.showToasterError("Sangh profile image is required");
      return;
    }
    this.addSangh(formdata);
  }

  async presentAlertPrompt(formdata) {
    const isYes = await this.utilityService.presentConfirm(
      'If every Sangh detail entered is correct, click Ok to Add Sangh else click Cancel',
      'Cancel',
      'Ok'
    );
    if (isYes) {
      this.alert.showSpinner();
      this.httpRequestService.post(api.addSangh, formdata).then((res: any) => {
        this.alert.showToaster(res.message);
        this.santService.sanghInformationForm.reset();
        this.navCtrl.navigateRoot(Roots.page + '/' + Roots.createNewSangh);
      }).finally(() => {
        this.alert.hideLoader();
      });
    }
  }

  async goToHome() {
    const isYes = await this.utilityService.presentConfirm(
      'Are you sure want to cancel?',
      'No',
      'Yes'
    );
    if (isYes) {
      this.navCtrl.navigateForward([Roots.page]);
    }
  }

}
