import { NgFor, NgIf } from '@angular/common';
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, FormsModule, ReactiveFormsModule, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { IonicSelectableComponent } from '@components/ionic-selectable/ionic-selectable.component';
import { api } from '@enums/api.enum';
import { constants } from '@enums/constants.enum';
import { Roots } from '@enums/root.enum';
import { CommonResponse, CompanyDetails, Privacy, ProfessionList } from '@interfaces/common';
import { WorkForm } 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-work',
  templateUrl: './shravak-edit-work.page.html',
  styleUrls: ['./shravak-edit-work.page.scss'],
  standalone: true,
  imports: [IonicModule, NgIf, FormsModule, ReactiveFormsModule, NgFor, IonicSelectableComponent]
})
export class ShravakEditWorkPage implements OnInit {
  privacyList: Privacy[] = constants.privacy;
  workForm: FormGroup<WorkForm>;
  professionDetails: Array<ProfessionList> = [];
  workId: number;
  workData: CompanyDetails;
  startYearValue = '';
  endYearValue = '';
  serializedForm: string;

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

  async ngOnInit() {
    if (this.router.getCurrentNavigation().extras.state) {
      this.workData = this.router.getCurrentNavigation().extras.state.workData;
      this.workId = this.workData.id;
      this.startYearValue = this.workData.start_year ? this.workData.start_year : '';
      this.endYearValue = this.workData.end_year ? this.workData.end_year : '';
    }

    this.workForm = new FormGroup<WorkForm>({
      work_id: new FormControl(this.workId ? this.workId : ''),
      company_name: new FormControl(this.workData?.company_name ? this.workData.company_name : '', Validators.required),
      company_name_privacy: new FormControl(this.workData?.company_name_privacy ?
        this.workData.company_name_privacy : 1, Validators.required),
      profession_id: new FormControl(null, Validators.required),
      profession_privacy: new FormControl(this.workData?.profession_privacy ? this.workData.profession_privacy : 2, Validators.required),
      profession: new FormControl(this.workData?.profession ? this.workData.profession : ''),
      profession_speciality: new FormControl(this.workData?.profession_speciality, Validators.required),
      profession_speciality_privacy: new FormControl(this.workData?.profession_speciality_privacy ?
        this.workData.profession_speciality_privacy : 2, Validators.required),
      position: new FormControl(this.workData?.position ? this.workData.position : ''),
      position_privacy: new FormControl(this.workData?.position_privacy ? this.workData.position_privacy : 2),
      website: new FormControl(this.workData?.website ? this.workData.website : ''),
      website_privacy: new FormControl(this.workData?.website_privacy ? this.workData.website_privacy : 2),
      city: new FormControl(this.workData?.city ? this.workData.city : ''),
      city_privacy: new FormControl(this.workData?.city_privacy),
      about: new FormControl(this.workData?.about ? this.workData.about : ''),
      about_privacy: new FormControl(this.workData?.about_privacy ? this.workData.about_privacy : 2),
      is_working: new FormControl(this.workData?.is_working ? this.workData.is_working : false, Validators.required),
      work_duration_privacy: new FormControl(this.workData?.work_duration_privacy ?
        this.workData.work_duration_privacy : 2, Validators.required),
      start_year: new FormControl(this.workData?.start_year ? this.workData.start_year : '', Validators.required),
      end_year: new FormControl(this.workData?.end_year ? this.workData.end_year : ''),
    });
    this.getProfessionList();
    this.serializedForm = this.getSerializedForm(this.workForm);
  }

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

  getProfessionList() {
    this.httpRequestService.get(api.professionList).then((res: CommonResponse) => {
      this.professionDetails = res.data;
      this.professionDetails.forEach((elem) => {
        if (this.workData && (elem.id === this.workData.profession_id)) {
          this.workForm.controls.profession_id.setValue(elem);
        }
      });
    });
  }

  // update validation based on profession selection. Remove validation if Housewife selected
  updateValidation() {
    ['company_name', 'company_name_privacy', 'profession_speciality',
      'profession_speciality_privacy', 'is_working', 'start_year'
    ].forEach(key => {
      if (this.workForm.get('profession_id').value?.name === 'Housewife') {
        this.workForm.get(key).clearValidators();
      } else {
        this.workForm.get(key).setValidators([Validators.required]);
      }
      this.workForm.get(key).updateValueAndValidity();
    });
  }

  onSubmit() {
    this.updateValidation();
    const form = this.workForm;
    if (form.value.profession_id?.id) {
      if (form.value.profession_id.name !== 'Other') {
        form.controls.profession.setValue(form.value.profession_id.name);
      }
      form.controls.profession_id.setValue(form.value.profession_id);
    }
    if (!form.valid) {
      this.professionDetails.forEach((ele) => {
        if (ele.id === form.value.profession_id?.id) {
          form.controls.profession_id.setValue(ele);
        }
      });
      form.markAllAsTouched();
      return;
    }
    const formWithoutProfId = JSON.parse(JSON.stringify(form.value));
    formWithoutProfId.profession_id = '';
    if (this.serializedForm === JSON.stringify(formWithoutProfId)) {
      this.professionDetails.forEach((ele) => {
        if (ele.id === form.value.profession_id.id) {
          form.controls.profession_id.setValue(ele);
        }
      });
      this.alert.showToaster('No changes to save');
      return;
    }

    const payload = {
      ...form.value,
      profession_id: form.value.profession_id.id
    };
    this.httpRequestService.post(api.updateShravakProfile, { company_details: [payload] }).then((res: CommonResponse) => {
      this.professionDetails.forEach((ele) => {
        if (ele.id === form.value.profession_id.id) {
          form.controls.profession_id.setValue(ele);
        }
      });
      this.navCtrl.navigateBack(Roots.page + '/' + Roots.shravakAbout);
      this.alert.showToaster(res.message);
    }).catch(() => {
      this.professionDetails.forEach((ele) => {
        if (ele.id === form.controls.profession_id.value.id) {
          form.controls.profession_id.setValue(ele);
        }
      });
    });
  }

  formatDate(value, type) {
    if (!value) { return; }
    if (type === 1) {
      this.workForm.controls.start_year.setValue(format(parseISO(value), 'yyyy'));
    } else if (type === 2) {
      this.workForm.controls.end_year.setValue(format(parseISO(value), 'yyyy'));
    }
    return format(parseISO(value), 'yyyy');
  }

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

  changeProfession(event) {
    if (event.value.id === 10) {
      this.workForm.controls.profession.setValidators([Validators.required]);
    } else {
      this.workForm.controls.profession.clearValidators();
    }
    this.workForm.controls.profession.setValue('');
    this.workForm.controls.profession.updateValueAndValidity();
  }

}
