import { DOCUMENT, DatePipe, NgClass, NgFor, NgIf } from '@angular/common';
import { Component, Inject, OnInit, Renderer2 } from '@angular/core';
import { FormGroup, FormsModule, ReactiveFormsModule, Validators } from '@angular/forms';
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 { Dharma, Sampraday } from '@interfaces/common';
import { SanghInformationForm } from '@interfaces/form';
import { IonicModule, NavController } from '@ionic/angular';
import { HttpRequestService } from '@services/http-request.service';
import { SantInfoService } from '@services/sant-info.service';
import { StateManagementService } from '@services/state-management.service';
import { UtilityService } from '@services/utility.service';
import { format, parseISO } from 'date-fns';
@Component({
  selector: 'app-sangh-information',
  templateUrl: './sangh-information.page.html',
  styleUrls: ['./sangh-information.page.scss'],
  standalone: true,
  imports: [IonicModule, FormsModule, ReactiveFormsModule, NgIf, NgFor, NgClass, IonicSelectableComponent, GjDatetimeDirective, DatePipe]
})
export class SanghInformationPage implements OnInit {
  sanghInformationForm: FormGroup<SanghInformationForm>;
  dateValue = '';
  sampradayDetails: Array<Sampraday> = [];
  dharmaDetails: Array<Dharma> = [];
  sanghList = [];
  currentDate = this.formatDate((new Date()).toISOString());
  sanghRegDate = '';
  sanghTypes = constants.sanghTypes;
  templeType = [];
  mulnayakBhagwan = [];
  prevValue: string;

  constructor(
    private navCtrl: NavController,
    public santService: SantInfoService,
    private stateManagementService: StateManagementService,
    private httpRequestService: HttpRequestService,
    private renderer: Renderer2,
    @Inject(DOCUMENT) private document: Document,
    public utilityService: UtilityService
  ) { }

  ngOnInit() {
    this.renderer.addClass(this.document.body, 'demo-class');
    this.sanghInformationForm = this.santService.sanghInfoForm;
    this.templeType = this.stateManagementService?.common?.data?.derasar_type ?? [];
    this.mulnayakBhagwan = this.stateManagementService?.common?.data?.mulnayak_bhagwan ?? [];

    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;
      this.sampradayDetails.forEach((elem) => {
        if (elem?.id === this.sanghInformationForm.controls.sampraday_id.value?.id) {
          this.sanghInformationForm.controls.sampraday_id.setValue(elem);
        }
      });
    } else {
      this.getSampradayDetails();
    }
    this.renderer.addClass(this.document.body, 'sangh-selectable');
  }

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

  getSampradayDetails() {
    const params = {
      dharma_id: this.santService.sanghInfoForm.controls.dharma_id.value
    };
    this.httpRequestService.get(api.sampradayDetails, params).then((res: any) => {
      this.sampradayDetails = res.data;
      this.stateManagementService.sampradayDetails = res.data;
      if (this.sampradayDetails) {
        this.sampradayDetails.forEach((elem) => {
          if (elem?.id === this.sanghInformationForm.controls.sampraday_id.value?.id) {
            this.sanghInformationForm.controls.sampraday_id.setValue(elem);
          }
        });
      }
    });
  }

  getSanghList(event) {
    if (!event.value.trim() || !this.sanghInformationForm.controls.dharma_id?.value ||
      !this.sanghInformationForm?.controls.sampraday_id.value?.id) {
      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(): void {
    this.sanghInformationForm.controls.sampraday_id.setValue(null);
    this.getSampradayDetails();
  }

  moveToNext(form) {
    if (form.value.reg_date) {
      form.value.reg_date = this.formatDate(form.value.reg_date);
    }
    if (!form.valid) {
      this.sanghInformationForm.markAllAsTouched();
      return;
    }
    this.navCtrl.navigateForward(Roots.page + '/' + Roots.sanghAddress);
  }

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

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

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

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