import { NgFor, NgIf } from '@angular/common';
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, FormsModule, ReactiveFormsModule, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { api } from '@enums/api.enum';
import { constants } from '@enums/constants.enum';
import { Roots } from '@enums/root.enum';
import { College, CommonResponse, Privacy } from '@interfaces/common';
import { CollegeForm, HighSchoolForm } from '@interfaces/form';
import { IonicModule, NavController } from '@ionic/angular';
import { AlertService } from '@services/alert.service';
import { HttpRequestService } from '@services/http-request.service';
import { format, parseISO } from 'date-fns';

@Component({
  selector: 'app-shravak-edit-education',
  templateUrl: './shravak-edit-education.page.html',
  styleUrls: ['./shravak-edit-education.page.scss'],
  standalone: true,
  imports: [IonicModule, NgIf, FormsModule, ReactiveFormsModule, NgFor]
})
export class ShravakEditEducationPage implements OnInit {
  privacyList: Privacy[] = constants.privacy;
  yearValue = '';
  endYearValue = '';
  type: string;
  id: number;
  collegeForm: FormGroup<CollegeForm>;
  highSchoolForm: FormGroup<HighSchoolForm>;
  qualificationData: College;
  serializedForm: string;

  constructor(
    private cRoute: ActivatedRoute,
    private httpRequestService: HttpRequestService,
    private alert: AlertService,
    private navCtrl: NavController,
    private router: Router,
  ) { }

  async ngOnInit() {
    this.type = this.cRoute.snapshot.paramMap.get('type');
    if (this.router.getCurrentNavigation().extras.state) {
      this.qualificationData = this.router.getCurrentNavigation().extras.state.qualificationData;
      this.id = this.qualificationData.id;
      this.type = this.router.getCurrentNavigation().extras.state.type;
    }
    if (this.type === '1') {
      this.highSchoolForm = new FormGroup<HighSchoolForm>({
        qualification_id: new FormControl(this.id ? this.id : ''),
        type: new FormControl('2'),
        highschool: new FormControl(this.id ? this.qualificationData.highschool : '', Validators.required),
        qualification: new FormControl(this.id ? this.qualificationData.qualification : '', Validators.required),
        passing_year: new FormControl(this.id ? this.qualificationData.passing_year : '', Validators.required),
        privacy: new FormControl((this.id && this.qualificationData.privacy) ? this.qualificationData.privacy : 1, Validators.required),
      }, {});
      if (this.id) {
        this.yearValue = this.qualificationData.passing_year ? this.qualificationData.passing_year : '';
      }
      this.serializedForm = this.getSerializedForm(this.highSchoolForm);
    } else if (this.type === '2') {
      this.collegeForm = new FormGroup<CollegeForm>({
        qualification_id: new FormControl(this.id ? this.id : ''),
        type: new FormControl('1'),
        university: new FormControl(this.id ? this.qualificationData.university : '', Validators.required),
        qualification: new FormControl(this.id ? this.qualificationData.qualification : '', Validators.required),
        is_graduate: new FormControl(this.id ? this.qualificationData.is_graduate : false),
        passing_year: new FormControl(this.id ? this.qualificationData.passing_year : ''),
        privacy: new FormControl((this.id && this.qualificationData.privacy) ? this.qualificationData.privacy : 1, Validators.required),
      }, {
      });
      if (this.id) {
        this.endYearValue = this.qualificationData.passing_year ? this.qualificationData.passing_year : '';
      }
      this.serializedForm = this.getSerializedForm(this.collegeForm);
    }
  }

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

  formatDate(value, type) {
    if (!value) { return; }
    if (type === 1) {
      this.highSchoolForm.controls.passing_year.setValue(format(parseISO(value), 'yyyy'));
    } else if (type === 3) {
      this.collegeForm.controls.passing_year.setValue(format(parseISO(value), 'yyyy'));
    }
    return format(parseISO(value), 'yyyy');
  }

  onSubmitCollege(form) {
    if (!this.collegeForm.valid) {
      this.collegeForm.markAllAsTouched();
      return;
    }
    if (this.serializedForm === this.getSerializedForm(form)) {
      this.alert.showToaster('No changes to save');
      return;
    }
    this.httpRequestService.post(api.updateShravakProfile, { qualification_details: [form.value] })
      .then((res: CommonResponse) => {
        this.navCtrl.navigateBack(Roots.page + '/' + Roots.shravakAbout);
        this.alert.showToaster(res.message);
      });
  }

  onSubmitHighSchool(form) {
    if (!this.highSchoolForm.valid) {
      this.highSchoolForm.markAllAsTouched();
      return;
    }
    if (this.serializedForm === this.getSerializedForm(form)) {
      this.alert.showToaster('No changes to save');
      return;
    }
    this.httpRequestService.post(api.updateShravakProfile, { qualification_details: [form.value] })
      .then((res: CommonResponse) => {
        this.navCtrl.navigateBack(Roots.page + '/' + Roots.shravakAbout);
        this.alert.showToaster(res.message);
      });
  }

  onChange(event) {
    if (event.detail.checked) {
      this.collegeForm.controls.passing_year.setValidators([Validators.required]);
    } else {
      this.collegeForm.controls.passing_year.clearValidators();
    }
    this.collegeForm.controls.passing_year.updateValueAndValidity();
    if (!this.collegeForm.controls.is_graduate.value) {
      this.collegeForm.controls.passing_year.setValue('');
      this.endYearValue = '';
    }
  }

}
