import { NgClass, NgFor, NgIf, TitleCasePipe } from '@angular/common';
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Share, ShareOptions } from '@capacitor/share';
import { FooterComponent } from '@components/footer/footer.component';
import { ProfileCompleteIndicatorComponent } from '@components/profile-complete-indicator/profile-complete-indicator.component';
import { SantLocationComponent } from '@components/sant-location/sant-location.component';
import { SantPostComponent } from '@components/sant-post/sant-post.component';
import { api } from '@enums/api.enum';
import { Roots } from '@enums/root.enum';
import { environment } from '@environments/environment';
import { SantActivityList } from '@interfaces/common';
import { IonicModule, NavController } from '@ionic/angular';
import { AlertService } from '@services/alert.service';
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';

@Component({
  selector: 'app-sant-view-profile',
  templateUrl: './sant-view-profile.page.html',
  styleUrls: ['./sant-view-profile.page.scss'],
  standalone: true,
  imports: [IonicModule, NgIf, NgFor, ProfileCompleteIndicatorComponent, NgClass, SantLocationComponent, SantPostComponent,
    FooterComponent, TitleCasePipe]
})
export class SantViewProfilePage implements OnInit {
  santId = '';
  updatedSantId = '';
  santDetails: any;
  santPageNumber = 1;
  santTotalPage = 1;
  santPostList: Array<SantActivityList> = [];

  constructor(
    private navCtrl: NavController,
    private activatedRoute: ActivatedRoute,
    private httpRequestService: HttpRequestService,
    private stateManagementService: StateManagementService,
    private alert: AlertService,
    private router: Router,
    private santService: SantInfoService,
    public utilityService: UtilityService
  ) { }

  async ngOnInit() {
    this.santId = this.activatedRoute.snapshot.paramMap.get('santId');
    this.updatedSantId = this.router.getCurrentNavigation().extras?.state?.updatedSantId;
  }

  ionViewWillEnter() {
    this.getSantDetails();
    this.getSantPostList(false, '');
    this.getDharmaDetails();
  }

  getSantDetails(loadSampraday = true) {
    let apiRoute = api.santInfo + '/' + this.santId;
    if (this.updatedSantId) {
      apiRoute = api.inReviewSantInfo + '/' + this.updatedSantId;
    }
    this.alert.showLoader();
    this.httpRequestService.get(apiRoute).then((res: any) => {
      this.santDetails = res.data;
      this.stateManagementService.santDetails = res.data;
      if (loadSampraday) { this.getSampradayDetails(); }
    }).finally(() => {
      this.alert.hideLoader();
    });
  }

  getSantPostList(isFirstLoad, event) {
    if (this.santPageNumber <= this.santTotalPage) {
      this.httpRequestService.post(api.santActivityList, {
        page: this.santPageNumber,
        limit: 5,
        sant_id: this.santId
      }).then((res: any) => {
        this.santTotalPage = res.data.last_page;
        this.santPostList.push(...res.data.data);
        if (isFirstLoad) { event.target.complete(); }
        this.santPageNumber = res.data.current_page + 1;
      });
    } else {
      event?.target?.complete();
    }
  }

  // for show dharma in edit sant
  getDharmaDetails() {
    this.httpRequestService.get(api.dharmaDetails).then((res: any) => {
      this.stateManagementService.dharmaDetails = res.data;
    });
  }
  // for show sampraday in edit sant
  getSampradayDetails() {
    const params = {
      dharma_id: this.santDetails.dharma_id
    };
    this.httpRequestService.get(api.sampradayDetails, params).then((res: any) => {
      this.stateManagementService.sampradayDetails = res.data;
    });
  }

  moveToChaurmas() {
    const navOption = {
      state: {
        dharmaId: this.santDetails?.dharma_id,
        sampradayId: this.santDetails?.sampraday_id,
        thanaMemberCount: this.santDetails?.thana_member_count,
      },
    };
    this.navCtrl.navigateForward(Roots.page + '/' + Roots.chaturmasInfo.replace(':santId', this.santId), navOption);
  }

  moveToVihar() {
    const navOption = {
      state: {
        thanaMemberCount: this.santDetails?.thana_member_count,
      },
    };
    this.navCtrl.navigateForward(Roots.page + '/' + Roots.viharInfo.replace(':santId', this.santId), navOption);
  }

  moveToThana() {
    const navOption = {
      state: {
        dharmaId: this.santDetails?.dharma_id,
      },
    };
    this.navCtrl.navigateForward(Roots.page + '/' + Roots.thanaList.replace(':santId', this.santId), navOption);
  }

  moveToSantBio() {
    this.navCtrl.navigateForward(Roots.page + '/' + Roots.santBio.replace(':santId', this.santId));
  }

  async followSant(event, santData: any) {

    const followSant = () => {
      event.stopPropagation();
      const params = {
        sant_id: +this.santId,
      };
      this.httpRequestService.post(api.followSant, params).then(() => {
        this.santDetails.is_user_following = !this.santDetails.is_user_following;
      });
    };

    if (santData.is_user_following) {
      const isYes = await this.utilityService.presentConfirm(
        'Are you sure you want to unfollow?',
        'No', 'Yes', 'Unfollow'
      );
      if (isYes) {
        followSant();
      }
    } else {
      followSant();
    }
  }

  intlFormat(num) {
    return new Intl.NumberFormat().format(Math.round(num * 10) / 10);
  }

  localizeCount(num) {
    if (num >= 1000000) {
      return this.intlFormat(num / 1000000) + 'M';
    }
    if (num >= 1000) {
      return this.intlFormat(num / 1000) + 'k';
    }
    return this.intlFormat(num);
  }

  editProfile() {
    if ((
      (!this.santDetails?.is_in_review && this.santDetails?.verification_status === 1) && !this.updatedSantId) ||
      (this.updatedSantId && [3, 5].includes(this.santDetails?.verification_status))
    ) {
      const santData = {} as any;
      for (const [formKey, formValue] of Object.entries(this.santService.santInformationForm.value)) {
        santData[formKey] = {};
        for (const [key] of Object.entries(formValue)) {
          santData[formKey][key] =
            formKey === 'santInfoForm' && key === 'sampraday_id' ? this.santDetails.sampraday :
              this.santDetails[key] || '';
        }
      }
      const typeOfUser = ['', 'user', 'sant'];
      santData.dikshaInfoForm.guru = this.santDetails.guru ? this.santDetails.guru.name : null;
      santData.dikshaInfoForm.guru_id = this.santDetails.guru ? this.santDetails.guru.id : null;
      santData.sansarikJeevanInfoForm.father_id = this.santDetails.father.length > 0 ?
        this.santDetails.father[0].relation_id : null;
      santData.sansarikJeevanInfoForm.father_type = this.santDetails.father.length > 0 ?
        typeOfUser[this.santDetails.father[0].relation_type] : null;
      santData.sansarikJeevanInfoForm.mother_id = this.santDetails.mother.length > 0 ?
        this.santDetails.mother[0].relation_id : null;
      santData.sansarikJeevanInfoForm.mother_type = this.santDetails.mother.length > 0 ?
        typeOfUser[this.santDetails.mother[0].relation_type] : null;
      this.santService.santInformationForm.patchValue(santData);
      this.santService.updateSant = true;
      this.santService.updateSantId = this.santId;
      this.santService.reviewed_fields = this.santDetails.reviewed_fields;
      this.navCtrl.navigateForward(Roots.page + '/' + Roots.santInfo);
    }
  }

  viewAllFollowers() {
    this.navCtrl.navigateForward([
      Roots.page + '/' + Roots.viewAll.replace(':santListType', '5'),
      { id: this.activatedRoute.snapshot.paramMap.get('santId') }
    ]);
  }

  async shareProfile() {
    const options: ShareOptions = {
      url: `${environment.siteUrl}/page/sant-view-profile/${this.santId}`,
    };
    await Share.share(options);
  }

  goToInReview() {
    this.stateManagementService.generalData.pending_sant_action = 0;
    this.stateManagementService.pushNotyObservable.next(this.stateManagementService.generalData);
    this.navCtrl.navigateForward(Roots.page + '/' + Roots.viewAll.replace(':santListType', '1'));
  }

}
