import { DOCUMENT, DatePipe, NgClass, NgFor, NgIf, TitleCasePipe } from '@angular/common';
import { Component, Inject, OnInit, Renderer2 } from '@angular/core';
import { FormGroup, FormsModule, ReactiveFormsModule } 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 { Roots } from '@enums/root.enum';
import { Dharma, Sampraday } from '@interfaces/common';
import { SantInformationForm } 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-sant-information',
  templateUrl: './sant-information.page.html',
  styleUrls: ['./sant-information.page.scss'],
  standalone: true,
  imports: [IonicModule, FormsModule, ReactiveFormsModule, NgFor, NgIf, NgClass, IonicSelectableComponent, GjDatetimeDirective,
    TitleCasePipe, DatePipe]
})
export class SantInformationPage implements OnInit {
  santInformationForm: FormGroup<SantInformationForm>;
  sampradayDetails: Array<Sampraday> = [];
  dharmaDetails: Array<Dharma> = [];
  honorArray = [];
  santList = [];
  honor = '';
  currentDate = this.formatDate((new Date()).toISOString());
  santBirthDate = '';
  prevValue: string;

  constructor(
    private navCtrl: NavController,
    private stateManagementService: StateManagementService,
    private httpRequestService: HttpRequestService,
    public santService: SantInfoService,
    public utilityService: UtilityService,
    private renderer: Renderer2,
    @Inject(DOCUMENT) private document: Document,
  ) {
    this.renderer.addClass(this.document.body, 'sant-selectable');
  }

  ngOnInit() {
    this.santInformationForm = this.santService.santInfoForm;
    if (this.santInformationForm) {
      this.santBirthDate = this.santInformationForm.controls.birth_date.value;
    }
    this.honorArray = this.santService.santInfoForm.controls.honor.value ? this.santService.santInfoForm.controls.honor.value : [];
    if (this.stateManagementService.dharmaDetails.length > 0) {
      this.dharmaDetails = this.stateManagementService.dharmaDetails;
    } else {
      this.getDharmaDetails();
    }
    this.setSamprday();
  }

  ionViewWillEnter() {
    this.setSamprday();
  }

  setSamprday() {
    if (this.stateManagementService.sampradayDetails.length > 0) {
      this.sampradayDetails = this.stateManagementService.sampradayDetails;
      this.sampradayDetails.forEach((elem) => {
        if (elem?.id === this.santInformationForm.controls.sampraday_id.value?.id) {
          this.santInformationForm.controls.sampraday_id.setValue(elem);
        }
      });
    } else {
      this.getSampradayDetails();
    }
  }

  addHonor(value) {
    if (value.replaceAll(/\s/g, '')) {
      this.honorArray.push(value);
      this.santInformationForm.controls.honor.setValue(this.honorArray);
      this.honor = '';
    }
  }

  removeHonor(index) {
    this.honorArray.splice(index, 1);
    this.santInformationForm.controls.honor.setValue(this.honorArray);
  }

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

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

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

  getSantList(event) {
    if (!event.value.trim()) { return this.santList = []; }
    const isSameStr = this.utilityService.isSameStr(event.value, this.prevValue, true);
    this.prevValue = event.value;
    if (!isSameStr) {
      this.httpRequestService.get(api.santList, {
        name: event.value.trim(),
        dharma_id: this.santInformationForm.controls.dharma_id.value,
        sampraday_id: this.santInformationForm.controls.sampraday_id.value.id,
        page: 1,
        limit: 10,
      }).then((res: any) => {
        if (event.value) { this.santList = res.data.data; }
      });
    }
  }

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

  moveToNext(form) {
    if (form.value.birth_date) {
      this.santInformationForm.controls.birth_date.setValue(this.formatDate(form.value.birth_date));
      form.value.birth_date = this.formatDate(form.value.birth_date);
    }
    if (!form.valid) {
      this.santInformationForm.markAllAsTouched();
      return;
    }
    this.navCtrl.navigateForward(Roots.page + '/' + Roots.aboutDiksha);
  }
}
