import { DatePipe, NgFor, NgIf } from '@angular/common';
import { Component, OnInit } from '@angular/core';
import { FormControl, 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 { GJainStorage } from '@enums/gjain-storage.enum';
import { Roots } from '@enums/root.enum';
import { BloodGroup, CommonResponse, Dharma, Jaati, MTongue, Privacy, ProfileData } from '@interfaces/common';
import { BasicInfoForm } from '@interfaces/form';
import { AlertController, IonicModule, NavController } from '@ionic/angular';
import { AlertService } from '@services/alert.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';

@Component({
  selector: 'app-shravak-edit-profile',
  templateUrl: './shravak-edit-profile.page.html',
  styleUrls: ['./shravak-edit-profile.page.scss'],
  standalone: true,
  imports: [IonicModule, NgIf, FormsModule, ReactiveFormsModule, NgFor, IonicSelectableComponent, GjDatetimeDirective, DatePipe]
})
export class ShravakEditProfilePage implements OnInit {
  privacyList: Privacy[] = constants.privacy;
  basicInfoForm: FormGroup<BasicInfoForm>;
  userProfileData: ProfileData;
  dharmaDetails: Array<Dharma> = [];
  jaatiDetails: Array<Jaati> = [];
  bloodGroupDetails: Array<BloodGroup> = [];
  motherTongueDetails: Array<MTongue> = [];
  maxDate: string;
  currentDate = this.formatDate((new Date()).toISOString());
  serializedForm: string;
  userBirthDateValue = '';
  marriageDateValue = '';
  constructor(
    private navCtrl: NavController,
    private alert: AlertService,
    private httpRequestService: HttpRequestService,
    private stateManagementService: StateManagementService,
    private alertController: AlertController,
    public utilityService: UtilityService
  ) {
    if (this.stateManagementService.dharmaDetails.length > 0) {
      this.dharmaDetails = this.stateManagementService.dharmaDetails;
    } else {
      this.getDharmaDetails();
    }
    if (this.stateManagementService.motherTongueDetails.length > 0) {
      this.motherTongueDetails = this.stateManagementService.motherTongueDetails;
    } else {
      this.getMotherTongueList();
    }
    if (this.stateManagementService.bloodGroupDetails.length > 0) {
      this.bloodGroupDetails = this.stateManagementService.bloodGroupDetails;
    } else {
      this.getBloodGroupList();
    }
  }

  async ngOnInit() {
    const userData = await this.stateManagementService.storage.get(GJainStorage.profileData);
    if (userData) {
      this.userProfileData = userData;
      this.basicInfoForm = new FormGroup<BasicInfoForm>({
        name: new FormControl(String(this.userProfileData.name), Validators.required),
        gender: new FormControl(String(this.userProfileData.gender_id), Validators.required),
        gender_privacy: new FormControl(this.userProfileData.gender_privacy, Validators.required),
        birth_date: new FormControl(this.userProfileData.birth_date),
        birth_date_privacy: new FormControl(this.userProfileData.birth_date_privacy),
        mother_tongue: new FormControl(this.userProfileData.mother_tongue_id,),
        mother_tongue_privacy: new FormControl(this.userProfileData.mother_tongue_privacy,),
        jati: new FormControl(),
        jati_privacy: new FormControl(this.userProfileData.jati_privacy,),
        dharma: new FormControl(this.userProfileData.dharma_id, Validators.required),
        dharma_privacy: new FormControl(this.userProfileData.dharma_privacy, Validators.required),
        blood_group: new FormControl(this.userProfileData.blood_group_id,),
        blood_group_privacy: new FormControl(this.userProfileData.blood_group_privacy,),
        marital_status: new FormControl(this.userProfileData.marital_status,),
        marital_status_privacy: new FormControl(this.userProfileData.marital_status_privacy,),
        marriage_anniversary: new FormControl(this.userProfileData.marriage_anniversary, []),
        marriage_anniversary_privacy: new FormControl(this.userProfileData.marriage_anniversary_privacy, []),
      }, {});
      this.maxDate = this.formatDate(new Date((new Date()).setFullYear((new Date()).getFullYear() - 14)).toISOString());
      this.userBirthDateValue = this.userProfileData.birth_date;
      this.marriageDateValue = this.userProfileData.marriage_anniversary;
    }
    this.getJaatiList(true);
    this.serializedForm = this.getSerializedForm(this.basicInfoForm);
  }

  onSubmit(form) {
    if (!this.basicInfoForm.valid) {
      this.basicInfoForm.markAllAsTouched();
      return;
    }
    form.controls.jati.setValue(this.basicInfoForm.controls.jati.value ? this.basicInfoForm.controls.jati.value.id : null);
    if (this.serializedForm === this.getSerializedForm(form)) {
      this.alert.showToaster('No changes to save');
      return;
    }
    this.httpRequestService.post(api.updateShravakProfile, form.value).then((res: CommonResponse) => {
      this.navCtrl.navigateBack(Roots.page + '/' + Roots.shravakAbout);
      this.alert.showToaster(res.message);
    });
  }

  getSerializedForm(form) {
    const formObj = form.getRawValue();
    return JSON.stringify(formObj);
  }

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

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

  getJaatiList(isFirst?: boolean) {
    this.httpRequestService.get(api.jaatiList).then((res: any) => {
      this.jaatiDetails = res.data;
      if (isFirst) {
        this.jaatiDetails.forEach((elem) => {
          if (elem.id === this.userProfileData.jati_id) {
            this.basicInfoForm.controls.jati.setValue(elem);
          }
        });
      }
    });
  }

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

  getBloodGroupList() {
    this.httpRequestService.get(api.bloodGroupList).then((res: any) => {
      this.bloodGroupDetails = res.data;
      this.stateManagementService.bloodGroupDetails = res.data;
    });
  }

  async jaatiRequest() {
    const alert = await this.alertController.create({
      cssClass: 'my-custom-class',
      header: 'Add Jaati',
      message: 'Please add jaati here so admin will review and update in list after approval!',
      inputs: [
        {
          name: 'jaati',
          type: 'text',
          placeholder: 'Jaati'
        },
      ],
      buttons: [
        {
          text: 'Ok',
          handler: (data) => {
            const params = {
              name: data.jaati
            };
            if (data.jaati) {
              this.httpRequestService.post(api.addJaati, params).then((res: any) => {
                this.alert.showToaster(res.message);
              });
            } else {
              this.alert.showToasterError('Please enter jaati for make a request');
              return false;
            }
          }
        }, {
          text: 'Cancel',
          role: 'cancel',
          cssClass: 'secondary',
        }
      ]
    });
    await alert.present();
  }
}
