import { NgIf } from '@angular/common';
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormsModule, ReactiveFormsModule, Validators } from '@angular/forms';
import { Roots } from '@enums/root.enum';
import { SanghDonationForm } from '@interfaces/form';
import { IonicModule, NavController } from '@ionic/angular';
import { CameraGalleryService } from '@services/camera-gallery.service';
import { SantInfoService } from '@services/sant-info.service';
import { UtilityService } from '@services/utility.service';
import { ifscValidator } from 'src/app/validators/common.validator';
@Component({
    selector: 'app-sangh-donation',
    templateUrl: './sangh-donation.page.html',
    styleUrls: ['./sangh-donation.page.scss'],
    standalone: true,
    imports: [IonicModule, FormsModule, ReactiveFormsModule, NgIf]
})
export class SanghAddressPage implements OnInit {
    sanghDonationForm: FormGroup<SanghDonationForm>;
    constructor(
        private navCtrl: NavController,
        private utilityService: UtilityService,
        private cameraGalleryService: CameraGalleryService,
        public santService: SantInfoService
    ) { }

    ngOnInit() {
        this.sanghDonationForm = this.santService.sanghDonationForm;

        this.sanghDonationForm.get('bank_account_number').valueChanges.subscribe(value => {
            this.setConditionalValidators(value);
        });
    }

    setConditionalValidators(value: number): void {
        const ifscCodeControl = this.sanghDonationForm.get('bank_ifsc');
        const branchNameControl = this.sanghDonationForm.get('bank_branch');

        if (value) {
            ifscCodeControl.setValidators([Validators.required, ifscValidator]);
            branchNameControl.setValidators([Validators.required]);
        } else {
            ifscCodeControl.clearValidators();
            branchNameControl.clearValidators();
        }

        ifscCodeControl.updateValueAndValidity();
        branchNameControl.updateValueAndValidity();
    }


    moveToNext(form) {
        if (!form.valid) {
            this.sanghDonationForm.markAllAsTouched();
            return;
        }
        this.navCtrl.navigateForward(Roots.page + '/' + Roots.sanghProfileImage);
    }

    selectImages() {
        this.cameraGalleryService.selectImage(512, 512, false).then((imageData: { imgString: string; itemImage: Blob }) => {
            this.sanghDonationForm.controls.bank_qr_code_url.setValue(imageData.imgString);
            this.sanghDonationForm.controls.bank_qr_code.setValue(imageData.itemImage);
        });
    }

    profileView(url: string): void {
        this.utilityService.imagePreview(url);
    }

    removeImage(): void {
        this.sanghDonationForm.controls.bank_qr_code_url.setValue(null);
        this.sanghDonationForm.controls.bank_qr_code.setValue(null);
    }

}
