import { NgFor, NgIf, NgSwitch, NgSwitchCase, NgSwitchDefault } from '@angular/common';
import { Component, OnInit } from '@angular/core';
import { FooterComponent } from '@components/footer/footer.component';
import { api } from '@enums/api.enum';
import { Roots } from '@enums/root.enum';
import { CommonResponse, NotificationList, NotificationResponse } from '@interfaces/common';
import { AlertController, IonicModule, NavController } from '@ionic/angular';
import { SafeHtmlPipe } from '@pipes/safe-html.pipe';
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-notification',
  templateUrl: './notification.page.html',
  styleUrls: ['./notification.page.scss'],
  standalone: true,
  imports: [IonicModule, NgIf, NgFor, NgSwitch, NgSwitchCase, NgSwitchDefault, FooterComponent, SafeHtmlPipe]
})
export class NotificationPage implements OnInit {
  notificationList: Array<NotificationList> = [];
  pageNumber = 1;
  totalPage = 1;
  noDataFlag: boolean;
  totalCount: number;

  constructor(
    private httpRequestService: HttpRequestService,
    private alert: AlertService,
    private alertController: AlertController,
    private stateManagementService: StateManagementService,
    private navCtrl: NavController,
    private utilityService: UtilityService
  ) { }

  ngOnInit() {
    this.stateManagementService.generalData.unread_notification_count = 0;
    this.stateManagementService.pushNotyObservable.next(this.stateManagementService.generalData);
  }

  ionViewWillEnter() {
    this.getNotificationList(false, '');
  }

  getNotificationList(isFirstLoad, event) {
    if (this.pageNumber <= this.totalPage) {
      const params = {
        page: this.pageNumber,
        limit: 18
      };
      this.httpRequestService.get(api.notificationList, params).then((res: NotificationResponse) => {
        this.totalPage = res.data.last_page;
        this.noDataFlag = true;
        this.totalCount = res.data.total;
        this.notificationList.push(...res.data.data);
        if (isFirstLoad) { event?.target?.complete(); }
        this.pageNumber++;
      });
    } else {
      event?.target?.complete();
    }
  }

  loadNotificationData($event) {
    this.getNotificationList(true, $event);
  }

  async acceptDeclineFamilyStatus(notId: number, id: number, status: number, index: number) {
    if (status === 2) {
      const isYes = await this.utilityService.presentConfirm(
        'Are you sure about cancel this request?',
        'No', 'Yes', 'Cancel Request'
      );
      if (isYes) {
        const res: any = await this.httpRequestService.post(api.relationshipRequestChange, {
          from_id: id,
          status,
        });
        this.notificationList.splice(index, 1);
        this.alert.showToaster(res.message);
      }
    } else {
      this.presentAlertPrompt(notId, id, index);
    }
  }

  sendConnectionRequest(notId: number, userId: number, actionStatus: number, index: number) {
    this.httpRequestService.post(api.connectionRequestStatusUpdate, { receiver_id: userId, status: actionStatus })
      .then((res: CommonResponse) => {
        this.notificationList.splice(index, 1);
        this.alert.showToaster(res.message);
      });
  }

  notificationDelete(id, type?: number, index?: number) {
    this.httpRequestService.get(api.deleteNotification.replace('{id}', id))
      .then(() => {
        if (type === 1) {
          this.notificationList.splice(index, 1);
        }
      });
  }

  async presentAlertPrompt(notId: number, id: number, index: number) {
    const alert = await this.alertController.create({
      cssClass: 'my-custom-class',
      header: 'Add Relation',
      message: 'Please add your relation with this person!',
      inputs: [
        {
          name: 'familyRelation',
          type: 'text',
          placeholder: 'Relation'
        },
      ],
      buttons: [{
        text: 'Ok',
        handler: async (data) => {
          const params = {
            from_id: id,
            status: 1,
            relation: data.familyRelation
          };
          const res: any = await this.httpRequestService.post(api.relationshipRequestChange, params);
          this.notificationList.splice(index, 1);
          this.alert.showToaster(res.message);
        }
      }, {
        text: 'Cancel',
        role: 'cancel',
        cssClass: 'secondary',
      }]
    });

    await alert.present();
  }

  viewPublicProfile(notification: any, type: string, notificationType: string) {
    if (['CommentPost', 'LikePost', 'TagPost', 'NewSanghPost', 'NewFriendPost'].includes(notificationType)) {
      const navOption = {
        state: {
          postId: notification.extra_fields.from_id,
          type: type === 'shravak' ? '1' : '3'
        },
      };
      this.navCtrl.navigateForward(Roots.page + '/' + Roots.postDetail, navOption);
    } else {
      if (type === 'shravak') {
        this.navCtrl.navigateForward([Roots.page + '/' + Roots.shravakOtherProfile, { id: notification.extra_fields.user_id }]);
      } else if (type === 'sant') {
        if (notificationType === 'SantSendBack') {
          const navOption = {
            state: {
              updatedSantId: notification.extra_fields.from_id,
            },
          };
          this.navCtrl.navigateForward(Roots.page + '/' + Roots.santViewProfile.replace(':santId', notification.extra_fields.from_id)
            , navOption);
        } else {
          this.navCtrl.navigateForward([Roots.page + '/' + Roots.santViewProfile, { santId: notification.extra_fields.from_id }]);
        }
      } else if (type === 'sangh') {
        const sanghId: number = notification.extra_fields.sangh_id;
        this.navCtrl.navigateForward(Roots.page + '/' + Roots.sanghProfile.replace(':sanghId', String(sanghId)));
      } else if (notificationType === 'SanghMemberID') {
        this.navCtrl.navigateForward(Roots.page + '/' + Roots.sanghFeeds);
      }
    }
  }

  async acceptDeclineSanghMember(notification: any, status: number, index: number) {
    if (status === 2) {
      const isYes = await this.utilityService.presentConfirm(
        'Are you sure about decline this request?',
        'No', 'Yes', 'Decline'
      );
      if (isYes) {
        const params = {
          sangh_id: notification.extra_fields.sangh_id,
          user_id: notification.extra_fields.from_id,
          status,
          is_commiittee: notification.type === 'UserSentMemberRequest' ? 1 : 0,
        };
        this.httpRequestService.post(api.acceptDeclineSanghRequest, params).then((res: any) => {
          this.notificationList.splice(index, 1);
          this.alert.showToaster(res.message);
        });
      }
    } else {
      const params = {
        sangh_id: notification.extra_fields.sangh_id,
        user_id: notification.extra_fields.from_id,
        status,
        is_commiittee: notification.type === 'UserSentMemberRequest' ? 1 : 0,
      };
      this.httpRequestService.post(api.acceptDeclineSanghRequest, params).then((res: any) => {
        this.notificationList.splice(index, 1);
        this.alert.showToaster(res.message);
      });
    }
  }

  moveToProfile(notification) {
    if ([
      'AdminAcceptedMemberRequest',
      'AdminRemovedMember',
      'SanghAddedMember',
      'AdminDeclinedMemberRequest',
      'NewSanghPost',
      'SanghUpdatedMember',
      'SanghApproved',
      'SanghRejected'
    ].includes(notification.type)) {
      const sanghId: number = notification.extra_fields.sangh_id;
      this.navCtrl.navigateForward(Roots.page + '/' + Roots.sanghProfile.replace(':sanghId', String(sanghId)));
    } else if (notification.extra_fields.user_type === 'shravak' || notification.extra_fields.user_type === 'sangh') {
      this.navCtrl.navigateForward([Roots.page + '/' + Roots.shravakOtherProfile, { id: notification.extra_fields.user_id }]);
    } else if (notification.extra_fields.user_type === 'sant') {
      this.navCtrl.navigateForward([Roots.page + '/' + Roots.santViewProfile, { santId: notification.extra_fields.from_id }]);
    }
  }
}
