import { NgIf } from '@angular/common';
import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { api } from '@enums/api.enum';
import { Roots } from '@enums/root.enum';
import { ActionSheetController, AlertController, 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-sant-profile-image',
  templateUrl: './sant-profile-image.page.html',
  styleUrls: ['./sant-profile-image.page.scss'],
  standalone: true,
  imports: [IonicModule, NgIf, FormsModule, SafeUrlPipe]
})
export class SantProfileImagePage implements OnInit {
  @ViewChild('fileInput', { static: true }) fileInput: ElementRef;
  photo: any;
  confirmationFlag = false;
  constructor(
    private navCtrl: NavController,
    private alert: AlertService,
    private httpRequestService: HttpRequestService,
    public actionSheetCtrl: ActionSheetController,
    public santService: SantInfoService,
    public alertController: AlertController,
    private cameraGalleryService: CameraGalleryService,
    private utilityService: UtilityService
  ) { }

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

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

  async moveToNext() {
    if (!this.confirmationFlag) {
      return;
    }
    const formData = new FormData();
    for (const [, formValue] of Object.entries(this.santService.santInformationForm.value)) {
      for (const [key, value] of Object.entries(formValue)) {
        if (key !== 'sampraday_id') {
          formData.append(key, (value ? (value instanceof Array ? value.toString() : value) : ''));
        }
      }
    }
    formData.append('verification_status', '2');
    formData.append('sampraday_id', String(this.santService.santInfoForm.controls.sampraday_id.value.id));

    if (this.santService.updateSant) {
      if (typeof (this.santService.santProfileImage.controls.avatar.value) === 'string') {
        formData.delete('avatar');
      }
      this.updateSant(formData);
    } else {
      this.addSant(formData);
    }
  }

  addSant(formData) {
    this.presentAlertPrompt('add', formData);
  }

  updateSant(formData) {
    this.presentAlertPrompt('update', formData);
  }

  async presentAlert(redirectionPath) {
    const alert = await this.alertController.create({
      cssClass: 'sant-approval',
      backdropDismiss: false,
      message: `Thank you for submitting maharaj saheb's / mahasati's profile.
      GlobalJain admin will verify and confirm within 48 hours.
      You can review the progress in "In Review".
      Once approved, you will be awarded karmā points` ,
      buttons: [{
        text: 'Ok',
        handler: () => {
          this.navCtrl.navigateBack(redirectionPath);
        }
      }]
    });
    await alert.present();
  }

  moveToBack() {
    this.navCtrl.navigateBack('/' + Roots.page + '/' + Roots.aboutSansarikJeevan);
  }

  async presentAlertPrompt(type: string, formData) {
    const isYes = await this.utilityService.presentConfirm(
      'Are you sure that all information is correct?'
    );
    if (isYes) {
      if (type === 'add') {
        this.alert.showSpinner();
        this.httpRequestService.post(api.addSant, formData).then(() => {
          this.santService.santInformationForm.reset();
          this.presentAlert('page/create-new-sant');
        }).finally(() => {
          this.alert.hideLoader();
        });
      } else if (type === 'update') {
        this.alert.showSpinner();
        this.httpRequestService.post(api.updateSant + '/' + this.santService.updateSantId, formData).then((res: any) => {
          this.alert.showToaster(res.message);
          this.santService.updateSant = false;
          this.santService.reviewed_fields = null;
          this.santService.santInformationForm.reset();
          this.presentAlert('page/sant-view-profile/' + this.santService.updateSantId);
        }).finally(() => {
          this.alert.hideLoader();
        });
      }
    }
  }
}
