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 { api } from '@enums/api.enum';
import { constants } from '@enums/constants.enum';
import { Roots } from '@enums/root.enum';
import { CommonResponse, FamilyMember, FriendList, Privacy } from '@interfaces/common';
import { FamilyForm } from '@interfaces/form';
import { IonicModule, NavController } from '@ionic/angular';
import { AlertService } from '@services/alert.service';
import { HttpRequestService } from '@services/http-request.service';
import { UtilityService } from '@services/utility.service';

@Component({
  selector: 'app-shravak-edit-family-members',
  templateUrl: './shravak-edit-family-members.page.html',
  styleUrls: ['./shravak-edit-family-members.page.scss'],
  standalone: true,
  imports: [IonicModule, NgIf, FormsModule, ReactiveFormsModule, NgFor]
})
export class ShravakEditFamilyMembersPage implements OnInit {
  privacyList: Privacy[] = constants.privacy;
  familyForm: FormGroup<FamilyForm>;
  userList: Array<FriendList> = [];
  selectedRelation: any;
  familyData: FamilyMember;
  disableFlag = false;
  prevValue: string;

  constructor(
    private httpRequestService: HttpRequestService,
    private navCtrl: NavController,
    private alert: AlertService,
    private router: Router,
    private utilityService: UtilityService
  ) {
    if (this.router.getCurrentNavigation().extras.state) {
      this.familyData = this.router.getCurrentNavigation().extras.state.familyData;
    }
    this.disableFlag = this.familyData && this.familyData.id ? true : false;
  }

  ngOnInit() {
    this.familyForm = new FormGroup<FamilyForm>({
      memberName: new FormControl(this.disableFlag ? this.familyData.sent_users.name : '', Validators.required),
      relation: new FormControl(this.disableFlag ? this.familyData.relation : '', Validators.required),
      relationPrivacy: new FormControl(this.disableFlag ? this.familyData.relation_privacy : 1, Validators.required),
    }, {});
  }

  getUserList(event) {
    if (!event.value.trim()) {
      return this.userList = [];
    }
    const isSameStr = this.utilityService.isSameStr(event.value, this.prevValue);
    this.prevValue = event.value;
    if (!isSameStr) {
      const params = {
        name: event.value.trim()
      };
      this.httpRequestService.get(api.friendListForFamily, params).then((res: any) => {
        this.userList = res.data;
        this.selectedRelation = '';
      });
    }
  }

  addUser(user) {
    this.familyForm.patchValue({ memberName: user.name });
    this.selectedRelation = user;
    this.userList = [];
  }

  onSubmit(form) {
    if (!this.selectedRelation && !this.selectedRelation?.id) {
      this.alert.showToaster('Please select member from existing user list.');
      return;
    }
    if (!this.familyForm.valid) {
      this.familyForm.markAllAsTouched();
      return;
    }
    const formData = new FormData();
    formData.append('to_id', this.selectedRelation.id);
    formData.append('relation', form.value.relation);
    formData.append('relation_privacy', form.value.relationPrivacy);
    this.alert.showSpinner();
    this.httpRequestService.post(api.sendRelationshipList, formData).then((res: CommonResponse) => {
      this.navCtrl.navigateBack(Roots.page + '/' + Roots.shravakAbout);
      this.alert.hideLoader();
      this.alert.showToaster(res.message);
    }).catch(() => {
      this.alert.hideLoader();
    });
  }

  addRelation(value) {
    if (value) {
      this.familyForm.controls.relation.clearValidators();
      this.familyForm.controls.relation.updateValueAndValidity();
    }
  }

  editRelationship() {
    if (!this.familyForm.valid) {
      this.familyForm.markAllAsTouched();
      return;
    }
    const params = {
      relation: this.familyForm.controls.relation.value,
      relation_privacy: this.familyForm.controls.relationPrivacy.value,
    };
    this.alert.showSpinner();
    this.httpRequestService.post(api.editFamilyRelation.replace('{id}', String(this.familyData.id)), params).then((res: CommonResponse) => {
      this.navCtrl.navigateBack(Roots.page + '/' + Roots.shravakAbout);
      this.alert.hideLoader();
      this.alert.showToaster(res.message);
    }).catch(() => {
      this.alert.hideLoader();
    });
  }

}
