import { NgFor, NgIf } from '@angular/common';
import { Component, NgZone, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Share, ShareOptions } from '@capacitor/share';
import { FooterComponent } from '@components/footer/footer.component';
import { PostComponent } from '@components/post/post.component';
import { api } from '@enums/api.enum';
import { GJainStorage } from '@enums/gjain-storage.enum';
import { Roots } from '@enums/root.enum';
import { environment } from '@environments/environment';
import { CommonResponse, ProfileData, ProfileResponse, UserData } from '@interfaces/common';
import { 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';

@Component({
  selector: 'app-shravak-other-profile',
  templateUrl: './shravak-other-profile.page.html',
  styleUrls: ['./shravak-other-profile.page.scss'],
  standalone: true,
  imports: [IonicModule, NgIf, NgFor, PostComponent, FooterComponent]
})
export class ShravakOtherProfilePage implements OnInit {
  userProfileData: ProfileData;
  userData: UserData;
  postList = [];
  pageNumber = 1;
  totalPage = 1;
  constructor(
    private cRoute: ActivatedRoute,
    private httpRequestService: HttpRequestService,
    private alert: AlertService,
    private navController: NavController,
    private ngZone: NgZone,
    private stateManagementService: StateManagementService,
    public utilityService: UtilityService
  ) { }

  async ngOnInit() {
    this.userData = await this.stateManagementService.storage.get(GJainStorage.userData);
  }

  ionViewWillEnter() {
    this.getProfileInfo();
    this.pageNumber = 1;
    this.getPostList(false, '');
    this.postList = [];
  }

  getProfileInfo() {
    this.httpRequestService.get(api.shravakPublicProfile.replace('{id}', this.cRoute.snapshot.paramMap.get('id')))
      .then((res: ProfileResponse) => {
        this.userProfileData = res.data;
        this.userProfileData.is_blocked = res.data.is_blocked;
      });
  }

  getPostList(isFirstLoad, event) {
    if (this.pageNumber <= this.totalPage) {
      this.httpRequestService.get(api.userPostList, {
        page: this.pageNumber,
        limit: 5,
        user_id: this.cRoute.snapshot.paramMap.get('id')
      }).then((res: any) => {
        this.totalPage = res.data.last_page;
        this.postList.push(...res.data.data);
        if (isFirstLoad) { event.target.complete(); }
        this.pageNumber++;
      });
    } else {
      event.target?.complete();
    }
  }

  loadData($event) {
    this.getPostList(true, $event);
  }

  goToAboutInfo() {
    const navOption = {
      state: {
        userData: this.userProfileData,
      },
    };
    this.navController.navigateForward(Roots.page + '/' + Roots.shravakAboutOther, navOption);
  }

  async shareProfile() {
    const options: ShareOptions = {
      url: `${environment.siteUrl}/page/shravak-other-profile/${this.userProfileData.id}`,
    };
    await Share.share(options);
  }

  sendConnectionRequest(id: number, status: number, actionStatus?: number) {
    if (status === 0 || status === 1) {
      this.confirmationAlert(status, id);
    } else {
      if (status === 4) {
        this.httpRequestService.post(api.connectionRequestSend, { receiver_id: id })
          .then((res: CommonResponse) => {
            this.userProfileData.request_status = 0;
            this.alert.showToaster(res.message);
          });
      } else if (status === 3) {
        this.httpRequestService.post(api.connectionRequestStatusUpdate, { receiver_id: id, status: actionStatus })
          .then((res: CommonResponse) => {
            if (actionStatus === 1) {
              this.userProfileData.request_status = 1;
            } else {
              this.userProfileData.request_status = 4;
            }
            this.alert.showToaster(res.message);
          });
      }
    }
  }

  async confirmationAlert(status, id?) {
    let message = '';
    if (status === 0) {
      message = 'Are you sure about to cancel this request?';
    } else if (status === 1) {
      message = 'Are you sure you want to remove User ' + this.userProfileData.name + ' from your connection?';
    }
    const isYes = await this.utilityService.presentConfirm(message);
    if (isYes) {
      this.httpRequestService.post(api.connectionRequestStatusUpdate, { receiver_id: id, status: 2 })
        .then((res: CommonResponse) => {
          this.userProfileData.request_status = 4;
          this.alert.showToaster(res.message);
        });
    }
  }

  moveToMessage() {
    this.ngZone.run(() => this.navController.navigateForward([Roots.page + '/' + Roots.messageChat, {
      userId: this.userProfileData?.id,
      name: this.userProfileData?.name
    }])).then();
  }


  goToFriendList() {
    if (this.userProfileData.request_status === 1) {
      this.navController.navigateForward([Roots.page + '/' + Roots.friendList, { id: this.cRoute.snapshot.paramMap.get('id') }]);
    }
  }
  viewAllSangh(sanghListType) {
    if (this.userProfileData.id && this.userProfileData.request_status === 1) {
      this.navController.navigateForward([
        Roots.page + '/' + Roots.viewAllSangh.replace(':sanghListType', sanghListType),
        { id: this.userProfileData.id }
      ]);
    }
  }

  address(type: string) {
    if (type === 'native') {
      this.utilityService.openGoogleMap(this.userProfileData.native_latitude, this.userProfileData.native_longitude);
    } else if (type === 'current') {
      this.utilityService.openGoogleMap(this.userProfileData.latitude, this.userProfileData.longitude);
    }
  }

  openReport() {
    this.utilityService.openReport({ userId: this.userProfileData.id, type: 'shravak' });
  }

  async blockUser() {
    const isYes = await this.utilityService.presentConfirm(
      `Are you sure you want to ${this.userProfileData.is_blocked ? 'unblock' : 'block'} this user?`
    );
    if (isYes) {
      const status = this.userProfileData.is_blocked ? 0 : 1; // 0: Unblock, 1: Block
      this.alert.showLoader();
      this.httpRequestService.post(api.blockThisUser, {
        id: this.userProfileData.id,
        status // 0: Unblock, 1: Block
      })
        .then((res: CommonResponse) => {
          this.userProfileData.is_blocked = status;
          this.userProfileData.request_status = 4;
          this.alert.showToaster(res.message);
        }).finally(() => {
          this.alert.hideLoader();
        });
    }
  }
}
