import { DatePipe, DOCUMENT, NgClass, NgFor, NgIf } from '@angular/common';
import { Component, ElementRef, Inject, Renderer2, ViewChild } from '@angular/core';
import { FormControl, FormGroup, FormsModule, ReactiveFormsModule, Validators } from '@angular/forms';
import { ActivatedRoute } from '@angular/router';
import { IonicSelectableComponent } from '@components/ionic-selectable/ionic-selectable.component';
import { GjDatetimeDirective } from '@directives/gj-datetime.directive';
import { api } from '@enums/api.enum';
import { constants } from '@enums/constants.enum';
import { Roots } from '@enums/root.enum';
import { CommonResponse, Countries, Dharma, PhotoDetail, Sampraday, SanghProfileData } from '@interfaces/common';
import { IonicModule, IonModal, 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 { StateManagementService } from '@services/state-management.service';
import { UtilityService } from '@services/utility.service';
import { format, parseISO } from 'date-fns';
import { accountNumberValidator, ifscValidator } from 'src/app/validators/common.validator';
@Component({
  selector: 'app-sangh-edit-profile',
  templateUrl: './sangh-edit-profile.page.html',
  styleUrls: ['./sangh-edit-profile.page.scss'],
  standalone: true,
  imports: [IonicModule, NgIf, FormsModule, ReactiveFormsModule, NgClass, NgFor, GjDatetimeDirective, DatePipe,
    SafeUrlPipe, IonicSelectableComponent]
})
export class SanghEditProfilePage {
  @ViewChild('location') location: ElementRef;
  @ViewChild('confirmCancelModel') confirmCancelModel: IonModal;

  sanghInformationForm: FormGroup<any>;
  sanghData: SanghProfileData;
  dateValue = '';
  sampradayDetails: Array<Sampraday> = [];
  dharmaDetails: Array<Dharma> = [];
  sanghList = [];
  currentDate = this.formatDate((new Date()).toISOString());
  sanghRegDate: any;
  sanghTypes = constants.sanghTypes;
  prevValue: string;
  members = [];
  templeType = [];
  mulnayakBhagwan = [];
  countryCodes = [];
  students = [];
  books = [];
  confirmOptions = constants.confirmOptions;
  qrCode = new PhotoDetail();
  numLength = 10;

  constructor(
    private cRoute: ActivatedRoute,
    private httpRequestService: HttpRequestService,
    private alert: AlertService,
    private navCtrl: NavController,
    private stateManagementService: StateManagementService,
    private renderer: Renderer2,
    @Inject(DOCUMENT) private document: Document,
    private cameraGalleryService: CameraGalleryService,
    public utilityService: UtilityService
  ) {
    this.getProfileInfo();
    this.members = this.stateManagementService?.common?.data?.number_of_members ?? [];
    this.templeType = this.stateManagementService?.common?.data?.derasar_type ?? [];
    this.mulnayakBhagwan = this.stateManagementService?.common?.data?.mulnayak_bhagwan ?? [];
    this.students = this.stateManagementService?.common?.data?.number_of_students ?? [];
    this.books = this.stateManagementService?.common?.data?.number_of_books ?? [];

    if (this.stateManagementService.dharmaDetails.length > 0) {
      this.dharmaDetails = this.stateManagementService.dharmaDetails;
    } else {
      this.getDharmaDetails();
    }
    if (this.stateManagementService.sampradayDetails.length > 0) {
      this.sampradayDetails = this.stateManagementService.sampradayDetails;
    } else {
      this.getSampradayDetails();
    }
    this.renderer.addClass(this.document.body, 'sangh-selectable');
  }

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

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

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

  setDefaultCountryCode() {
    this.countryCodes.forEach((elem) => {
      if (elem.iso === 'IN') {
        this.sanghInformationForm.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();
      }
    });
  }

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

  ionViewWillEnter() {
    this.getProfileInfo();
  }

  getProfileInfo() {
    this.httpRequestService.get(api.sanghProfile.replace('{id}', this.cRoute.snapshot.paramMap.get('id'))).then((res: any) => {
      this.sanghData = res.data;
      this.sanghInformationForm = new FormGroup<any>({
        sangh_type: new FormControl(this.sanghData.sangh_type, Validators.required),
        name: new FormControl(this.sanghData.name, Validators.required),
        dharma_id: new FormControl(this.sanghData.dharma_id),
        sampraday_id: new FormControl(this.sanghData.sampraday_id),
        reg_number: new FormControl(this.sanghData.reg_number),
        mulnayak_bhagwan_name: new FormControl(null),
        type_of_template: new FormControl(this.sanghData.type_of_template),
        reg_date: new FormControl(this.sanghData.reg_date),
        number_of_members: new FormControl(this.sanghData.number_of_members, Validators.required),

        address: new FormControl(this.sanghData.address, Validators.required),
        city: new FormControl(this.sanghData.city, Validators.required),
        state: new FormControl(this.sanghData.state, Validators.required),
        longitude: new FormControl(this.sanghData.longitude, Validators.required),
        latitude: new FormControl(this.sanghData.latitude, Validators.required),
        about: new FormControl(this.sanghData.about),
        mobile_number: new FormControl(this.sanghData.mobile_number, Validators.required),
        email: new FormControl(this.sanghData.email, Validators.email),
        sangh_website: new FormControl(this.sanghData.sangh_website),
        apartment_name: new FormControl(this.sanghData.apartment_name),

        aaradhana_bhavan_status: new FormControl(this.sanghData.aaradhana_bhavan_status ?? 0, Validators.required),
        pathshala_status: new FormControl(this.sanghData.pathshala_status ?? 0, Validators.required),
        no_of_students: new FormControl(this.sanghData.no_of_students),
        library_status: new FormControl(this.sanghData.library_status ?? 0, Validators.required),
        library_name: new FormControl(this.sanghData.library_name),
        librarian_name: new FormControl(this.sanghData.librarian_name),
        librarian_mobile_number: new FormControl(this.sanghData.librarian_mobile_number),
        phoneCode: new FormControl(null),
        number_of_books: new FormControl(this.sanghData.number_of_books),

        tifin_service_status: new FormControl(this.sanghData.tifin_service_status ?? 0, Validators.required),
        bhojanshala_status: new FormControl(this.sanghData.bhojanshala_status ?? 0, Validators.required),
        aayambilshala_status: new FormControl(this.sanghData.aayambilshala_status ?? 0, Validators.required),
        mahila_mandal_status: new FormControl(this.sanghData.mahila_mandal_status ?? 0, Validators.required),
        yuva_mandal_status: new FormControl(this.sanghData.yuva_mandal_status ?? 0, Validators.required),
        swapna_chadawa_organised_status: new FormControl(this.sanghData.swapna_chadawa_organised_status ?? 0),

        bank_account_number: new FormControl(this.sanghData.bank_account_number, accountNumberValidator),
        bank_ifsc: new FormControl(this.sanghData.bank_ifsc),
        bank_branch: new FormControl(this.sanghData.bank_branch),
        bank_upi_id: new FormControl(this.sanghData.bank_upi_id),
        bank_qr_code: new FormControl(null)
      }, {});

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

      this.onSanghTypeChange();
      this.onChangeFields(this.sanghData.pathshala_status, false)
      this.onChangeFields(this.sanghData.library_status, true)

      this.sanghRegDate = this.sanghData.reg_date;

      const mulnayak_bhagwan = this.stateManagementService?.common?.data?.mulnayak_bhagwan.find(e => e.id === this.sanghData.mulnayak_bhagwan_name);
      this.sanghInformationForm.controls.mulnayak_bhagwan_name.setValue(mulnayak_bhagwan);

      this.qrCode.url = this.sanghData.bank_qr_code;

      this.sampradayDetails.forEach((elem) => {
        if (elem.id === this.sanghData.sampraday_id) {
          this.sanghInformationForm.controls.sampraday_id.setValue(elem);
        }
      });

      if (this.stateManagementService.countryDetails.length > 0) {
        this.countryCodes = this.stateManagementService.countryDetails;
        this.setDefaultCountryCode();
      } else {
        this.fetchCountryCodes();
      }
    });
  }

  initAutocomplete(): void {
    this.utilityService.createAutocomplete(this.location.nativeElement, []).subscribe((details) => {
      const { city, state, apartment } = this.getCityAndState(details.address_components);

      city && this.sanghInformationForm.controls.city.setValue(city);
      state && this.sanghInformationForm.controls.state.setValue(state);
      apartment && this.sanghInformationForm.controls.apartment_name.setValue(apartment);
      this.sanghInformationForm.controls.address.setValue(this.location.nativeElement.value);
      this.sanghInformationForm.controls.latitude.setValue(details.geometry.location.lat());
      this.sanghInformationForm.controls.longitude.setValue(details.geometry.location.lng());
    });
  }

  getCityAndState(addressComponents: any): { city: string, state: string, apartment: string } {
    let city = '';
    let state = '';
    let apartment = '';

    addressComponents.forEach(component => {
      const types = component.types;
      if (types.includes('locality')) {
        city = component.long_name;
      }
      if (types.includes('administrative_area_level_1')) {
        state = component.long_name;
      }
      if (types.includes('subpremise')) {
        apartment = component.long_name;
      }
    });

    return { city, state, apartment };
  }

  removeLatAndLong() {
    this.sanghInformationForm.controls.latitude.reset();
    this.sanghInformationForm.controls.longitude.reset();
  }

  onSubmit(form) {
    if (!this.sanghInformationForm.valid) {
      this.sanghInformationForm.markAllAsTouched();
      this.alert.showToasterError('Please fill required fields');
      return;
    }

    const apiUrl = api.updateSanghProfile.replace('{sangh_id}', String(this.cRoute.snapshot.paramMap.get('id')));
    if (form.value.sampraday_id && form.value.sampraday_id.id) {
      form.value.sampraday_id = form.value.sampraday_id.id;
    }

    if (form.value.mulnayak_bhagwan_name && form.value.mulnayak_bhagwan_name.id) {
      form.value.mulnayak_bhagwan_name = form.value.mulnayak_bhagwan_name.id;
    }

    if (form.value.reg_date) {
      form.value.reg_date = this.formatDate(form.value.reg_date);
    }
    this.presentAlertPrompt(apiUrl, form);
  }

  selectProfileImage() {
    this.cameraGalleryService.selectImage(512, 512, true).then((imageData: { imgString: string; itemImage: Blob }) => {
      if (imageData) {
        this.sanghData.avatar = imageData.imgString;
        const apiUrl = api.updateSanghProfile.replace('{sangh_id}', String(this.cRoute.snapshot.paramMap.get('id')));
        const formdata = new FormData();
        formdata.append('avatar', imageData.itemImage);
        this.httpRequestService.post(apiUrl, formdata).then((res: CommonResponse) => {
          this.sanghData.avatar = imageData.imgString;
          this.alert.showToaster(res.message);
        });
      }
    });
  }

  getDharmaDetails() {
    this.httpRequestService.get(api.dharmaDetails).then((res: any) => {
      this.dharmaDetails = res.data;
      this.stateManagementService.dharmaDetails = res.data;
    });
  }

  getSampradayDetails() {
    const params = {
      dharma_id: (this.sanghInformationForm && this.sanghInformationForm.controls.dharma_id.value)
        ? this.sanghInformationForm.controls.dharma_id.value : ''
    };
    this.httpRequestService.get(api.sampradayDetails, params).then((res: any) => {
      this.sampradayDetails = res.data;
      this.stateManagementService.sampradayDetails = res.data;
    });
  }

  getSanghList(event) {
    if (!event.value.trim()) {
      return this.sanghList = [];
    }

    const isSameStr = this.utilityService.isSameStr(event.value, this.prevValue, true);
    this.prevValue = event.value;
    if (!isSameStr) {
      const params = {
        name: event.value.trim(),
        dharma_id: this.sanghInformationForm.controls.dharma_id.value,
        sampraday_id: this.sanghInformationForm.controls.sampraday_id.value.id,
        page: 1,
        limit: 10,
      };
      this.httpRequestService.get(api.sanghSearchList, params).then((res: any) => {
        if (event.value) {
          this.sanghList = res.data.data;
        }
      });
    }
  }

  onDharmChange() {
    this.sanghInformationForm.controls.sampraday_id.setValue(null);
    this.getSampradayDetails();
  }

  formatDate(value) {
    return format(parseISO(value), 'yyyy-MM-dd');
  }

  async presentAlertPrompt(apiUrl, form) {
    const isYes = await this.utilityService.presentConfirm(
      'Are you sure that all information is correct?'
    );
    if (isYes) {
      const formValue = { ...form.value };

      if (+formValue.sangh_type === 1) {
        delete formValue.mulnayak_bhagwan_name;
        delete formValue.type_of_template;
        delete formValue.swapna_chadawa_organised_status;
      }

      const formdata = new FormData();
      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 (+this.sanghData.sangh_status === 2) {
        formdata.append('sangh_status', '0');
      }

      if (!this.sanghInformationForm?.controls?.bank_qr_code?.value) {
        formdata.append('bank_qr_code', '');
      }

      if (!this.sanghData?.avatar) {
        this.alert.showToasterError("Sangh profile image is required");
        return;
      }

      this.httpRequestService.post(apiUrl, formdata).then((res: CommonResponse) => {
        this.navCtrl.navigateBack([Roots.page + '/' + Roots.sanghProfile, { sanghId: this.cRoute.snapshot.paramMap.get('id') }]);
        this.alert.showToaster(res.message);
      });
    }
  }

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

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

  removeImage(): void {
    this.qrCode = new PhotoDetail();
    this.sanghInformationForm.controls.bank_qr_code.setValue(null);
  }

  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);
    }
  }

  onSanghTypeChange(): void {
    if (+this.sanghInformationForm?.controls?.sangh_type.value === 1) {
      this.sanghInformationForm.get('mulnayak_bhagwan_name').clearValidators();
      this.sanghInformationForm.get('type_of_template').clearValidators();
      this.sanghInformationForm.get('swapna_chadawa_organised_status').clearValidators();

    } else {
      this.sanghInformationForm.get('mulnayak_bhagwan_name').addValidators([Validators.required]);
      this.sanghInformationForm.get('type_of_template').addValidators([Validators.required]);
      this.sanghInformationForm.get('swapna_chadawa_organised_status').addValidators([Validators.required]);
    }
    this.sanghInformationForm.get('mulnayak_bhagwan_name').updateValueAndValidity();
    this.sanghInformationForm.get('type_of_template').updateValueAndValidity();
    this.sanghInformationForm.get('swapna_chadawa_organised_status').updateValueAndValidity();
  }

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

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

  onConfirm(ok = false) {
    this.confirmCancelModel.isOpen = false;
  }

  async onDelete() {
    this.confirmCancelModel.isOpen = true;
  }

  async resetDharm() {
    const isYes = await this.utilityService.presentConfirm(
      'Dharm and Sampraday values will reset. Please confirm!'
    );
    if (isYes) {
      this.sanghInformationForm.controls.dharma_id.setValue(null);
      this.sanghInformationForm.controls.sampraday_id.setValue(null);
    }
  }

}
