import { NgFor, NgIf } from '@angular/common';
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormsModule, ReactiveFormsModule, Validators } from '@angular/forms';
import { IonicSelectableComponent } from '@components/ionic-selectable/ionic-selectable.component';
import { api } from '@enums/api.enum';
import { constants } from '@enums/constants.enum';
import { Roots } from '@enums/root.enum';
import { Countries, Country } from '@interfaces/common';
import { SanghFacilitiesForm } from '@interfaces/form';
import { IonicModule, NavController } from '@ionic/angular';
import { AlertService } from '@services/alert.service';
import { HttpRequestService } from '@services/http-request.service';
import { SantInfoService } from '@services/sant-info.service';
import { StateManagementService } from '@services/state-management.service';
@Component({
    selector: 'app-sangh-facilities',
    templateUrl: './sangh-facilities.page.html',
    styleUrls: ['./sangh-facilities.page.scss'],
    standalone: true,
    imports: [IonicModule, FormsModule, ReactiveFormsModule, NgIf, IonicSelectableComponent, NgFor]
})
export class SanghFacilitiesPage implements OnInit {
    countryCodes: Array<Country> = [];
    sanghFacilitiesForm: FormGroup<SanghFacilitiesForm>;
    confirmOptions = constants.confirmOptions;
    numLength = 10;
    students = [];
    books = [];

    constructor(
        private httpRequestService: HttpRequestService,
        public santService: SantInfoService,
        private stateManagementService: StateManagementService,
        private navCtrl: NavController,
        private alert: AlertService
    ) { }

    ngOnInit() {
        this.sanghFacilitiesForm = this.santService.sanghFacilitiesForm;
    }

    ionViewWillEnter(): void {
        this.sanghFacilitiesForm = this.santService.sanghFacilitiesForm;
        if (+this.santService.sanghInfoForm?.controls?.sangh_type.value === 1) {
            this.removeControlValidation(['swapna_chadawa_organised_status']);
        } else {
            this.addControlValidation(['swapna_chadawa_organised_status']);
        }
        this.students = this.stateManagementService?.common?.data?.number_of_students ?? [];
        this.books = this.stateManagementService?.common?.data?.number_of_books ?? [];

        if (this.stateManagementService.countryDetails.length > 0) {
            this.countryCodes = this.stateManagementService.countryDetails;
            this.setDefaultCountryCode();
        } else {
            this.fetchCountryCodes();
        }
        this.onChangeFields(this.sanghFacilitiesForm.controls.library_status.value, true); // update validation for library felids
        this.onChangeFields(this.sanghFacilitiesForm.controls.pathshala_status.value, false); // update validation for pathsala felids
    }

    setDefaultCountryCode() {
        this.countryCodes.forEach((elem) => {
            if (elem.iso === 'IN') {
                this.sanghFacilitiesForm.controls.phoneCode.setValue(elem);
                this.codeChange({ value: { num_length: 10 } })
            }
        });
    }

    fetchCountryCodes() {
        this.httpRequestService.get(api.countryCodes).then((res: Countries) => {
            this.countryCodes = res.countries;
            this.stateManagementService.countryDetails = res.countries;
            if (this.countryCodes) {
                this.setDefaultCountryCode();
            }
        });
    }

    moveToNext(form) {
        if (!form.valid) {
            this.sanghFacilitiesForm.markAllAsTouched();
            this.alert.showToasterError('Please fill required fields');
            return;
        }
        this.navCtrl.navigateForward(Roots.page + '/' + Roots.sanghDonation);
    }

    codeChange(event) {
        this.numLength = event.value.num_length;
        this.sanghFacilitiesForm.controls.librarian_mobile_number.setValidators([Validators.required, Validators.pattern(`^[0-9]{${this.numLength}}$`)]);
    }

    onChangeFields(event, library = false): void {
        let keys = [];
        if (library) {
            keys = ['library_name', 'librarian_name', 'librarian_mobile_number', 'number_of_books'];
            event ? this.addControlValidation(keys) : this.removeControlValidation(keys);
        } else {
            keys = ['no_of_students'];
            event ? this.addControlValidation(keys) : this.removeControlValidation(keys);
        }
    }

    removeControlValidation(keys: string[]): void {
        for (const key of keys) {
            if (this.sanghFacilitiesForm.get(key)) {
                this.sanghFacilitiesForm.get(key).clearValidators();
                this.sanghFacilitiesForm.get(key).updateValueAndValidity();
            }
        }
    }

    addControlValidation(keys: string[]): void {
        for (const key of keys) {
            if (this.sanghFacilitiesForm.get(key)) {
                if (key === 'librarian_mobile_number') {
                    this.sanghFacilitiesForm.get(key).setValidators([Validators.required, Validators.pattern(`^[0-9]{${this.numLength}}$`)]);
                } else {
                    this.sanghFacilitiesForm.get(key).setValidators([Validators.required]);
                }
            }
        }
    }

}
