import { Component, ElementRef, HostListener, ViewChild } from '@angular/core';
import { LiveChatService } from '../../../../shared/services/admin/livechat.service';
import { Unsub } from '../../../../shared/class/unsub.class';
import { LoaderService } from '../../../../shared/services/loader.service';
import { Subscribable, Subscription, takeUntil } from 'rxjs';
import { AdminService } from '../../../../shared/services/admin/admin.service';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { ActivatedRoute, Router, RouterLink } from '@angular/router';
import { NgbDropdownModule, NgbModalModule, NgbTooltipModule } from '@ng-bootstrap/ng-bootstrap';
import { AgentMessageComponent } from '../chat-interface/agent-message/agent-message.component';
import { CustomerMessageComponent } from '../chat-interface/customer-message/customer-message.component';
import { CommentMessageComponent } from '../chat-interface/comment-message/comment-message.component';
import { FeedbackCommentComponent } from '../chat-interface/feedback-comment/feedback-comment.component';
import { NgSelectInputComponent } from '../../../../core/components/input/ng-select-input/ng-select-input.component';
import { LivechatViewComponent } from '../chat-interface/livechat-view/livechat-view.component';
import { CustomerInfoComponent } from '../chat-interface/customer-info/customer-info.component';
import { LiveChatSidebarComponent } from '../chat-interface/live-chat-sidebar/live-chat-sidebar.component';
import { LivechatSocketService } from '../../../../shared/services/livechat-socket.service';
import { TranslatePipes } from '../../../../shared/pipes/translate/translate.pipe';
import { LivechatDataService } from '../../../../shared/services/livechat-data.service';
import { AdminPageHeaderComponent } from '../../../../shared/common/pageheader/admin-page-header/admin-page-header.component';
import { ToastrService } from 'ngx-toastr';
import { TranslatePipe } from '@ngx-translate/core';

@Component({
  selector: 'app-newcharts',
  standalone: true,
  imports: [CommonModule, FormsModule, ReactiveFormsModule, RouterLink, TranslatePipes, NgbDropdownModule, NgbModalModule, NgbTooltipModule, LivechatViewComponent, CustomerInfoComponent, LiveChatSidebarComponent, TranslatePipes, AdminPageHeaderComponent],
  templateUrl: './newcharts.component.html',
  styleUrl: './newcharts.component.scss'
})
export class NewchartsComponent extends Unsub {
  data;
  settings
  pastMessage = '';
  newVal = '';
  id = null;
  operatorID;
  currentDate;
  autoUserInfo;
  reply = '';
  isChat = true;
  subscategory = null;
  AuthId;
  customerData;
  parsedChatFlowMessages: any[] = [];
  chatData
  timezone;
  operatorUser: any = null;
  constructor(private liceChatService: LiveChatService, private adminService: AdminService, private activatedRoute: ActivatedRoute, private liveChatDataService: LivechatDataService, private toastr: ToastrService, private translate: TranslatePipe,
    loaderService: LoaderService, private el: ElementRef, private LivechatSocketService: LivechatSocketService, private router: Router) {
    super(loaderService);
    this.autoUserInfo = localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user') as string) : null;
    this.activatedRoute.queryParams.pipe(takeUntil(this.unSubscribe$)).subscribe({
      next: (params: any) => {
        this.id = params.id;
        this.operatorID = params.operatorID;
        this.customerData = null
        this.chatData = null
        this.parsedChatFlowMessages = []
        this.operatorUser = null;

        this.newChatFn();
        this.adminService.RefreshRquestAdmin$.pipe(
          takeUntil(this.unSubscribe$)
        ).subscribe({
          next: () => {
            this.newChatFn();
          },
        });
      }
    })
  }
  ngOnInit() {
    this.LivechatSocketService.getUpdatedState().subscribe(value => {
      if (value === 'true') {
        this.liceChatService.newchat(this.operatorID)
          .pipe(takeUntil(this.unSubscribe$))
          .subscribe({
            next: (res) => {
              this.AuthId = res.userId;
              if (this.data != res) {
                this.data = res;
                this.users = res.user;
              }
            }
          })
      }
    });
  }
  newChat$: Subscription;
  newChatFn() {

    this.loaderService.showLoader();
    // this.isloader = true;
    this.newChat$ = this.liceChatService.newchat(this.operatorID)
      .subscribe({
        next: (res) => {
          this.liveChatDataService.updateData(res.filteredLiveCust);

          this.timezone = res.timezonedata;
          this.AuthId = res.userId;
          let NewUserId = null;
          for (let index = 0; index < res.filteredLiveCust.length; index++) {
            const element = res.filteredLiveCust[index];
            if (!element?.['lastMessage']?.['delete']) {
              NewUserId = element?.id;
              break;
            }
          }
          if (this.data != res) {
            if (this.id != NewUserId && !this.operatorID) {
              this.router.navigate([], {
                relativeTo: this.activatedRoute,
                queryParams: { id: NewUserId },
                queryParamsHandling: 'merge' // Merge with existing query params
              });
            }

            this.data = res;
            this.users = res.user;
          }
          if (this.operatorID) {
            this.findUserById(this.operatorID);
          }
          this.settings = res.settings;
          if (this.id) {
            this.sideMenuOpenClickFunction(NewUserId);
          }

        }
      })
  }
  findUserById(operatorID: number): any {
    this.operatorUser = this.data?.user?.find(user => user.id == operatorID);
  }
  // SideBar and Online operators loop click
  sideMenuOpenClickFunction(id) {
    this.liceChatService.singlecustdata(id).subscribe({
      next: data => {
        this.chatData = data;
        this.customerData = data.livechatcust;
        this.parsedChatFlowMessages = this.parse(data.livechatcust?.chat_flow_messages ?? "");
        this.parsedChatFlowMessages.forEach(res => {
          res.created_at = data.livechatcust.created_at;
          res.status = "seen";
          if (res.authMessage == "agent") {
            res.livechat_username = "chatBot"
          } else {
            res.livechat_username = data.livechatcust.username
          }
        })
        //         // To remove the Font Bold
        let unReadIndexNumber: HTMLElement = this.el.nativeElement.querySelector(".unReadIndexNumber");
        let chatMsg = this.el.nativeElement.querySelector(".chat-msg");
        if (chatMsg && (chatMsg?.classList.contains('font-weight-bold') || unReadIndexNumber)) {
          chatMsg?.classList.remove("font-weight-bold")
        }

        if (unReadIndexNumber) {
          unReadIndexNumber?.remove()
          let markAsUnreadBtn: HTMLAnchorElement = this.el.nativeElement.querySelector('.markAsUnreadBtn')
          // To Change the Make as read to Mark as unread
          if (markAsUnreadBtn) {
            markAsUnreadBtn?.['innerText'] == 'Mark As Read'
            if (markAsUnreadBtn) {
              markAsUnreadBtn.href = markAsUnreadBtn.href.replace("markasread", "markasunread");
              markAsUnreadBtn.innerHTML = `<i class="ri-chat-check-line align-start me-2 fs-18"></i> Mark As Unread`
            }
          }
        }

        //         // Message conversation logic
        let chatFooter = this.el.nativeElement.querySelector(".chat-footer") as HTMLElement;
        chatFooter?.classList.remove("d-none")


        // To Scroll Down the Conversation
        this.el.nativeElement.querySelector("#operator-conversation")?.scrollBy(0, (this.el.nativeElement.querySelector("#operator-conversation") as HTMLElement).scrollHeight)

        // Set the sidebar active
        localStorage.setItem("livechatCustomer", id ?? '')
      },
      error: err => {
      }
    })
  }
  parse(val) {
    if (val) {
      return JSON.parse(val);
    }
    return [];
  }
  fileUploadPermission(event, val) {
    let ele = event.target;
    let data = {
      permission: ele.checked,
      custUser: val?.id
    }
    this.liceChatService.livechatLiveChatCustFileupload(data).subscribe({
      next: res => {
        if (res.success) {
          this.toastr.success(this.translate.transform("Updated successfully"));
        }
      }
    })
  }
  updatemenu(value) {
    let customerIdEle: HTMLElement = this.el.nativeElement.querySelector(`.checkforactive[data-id='${value}']`);
    customerIdEle?.classList.add("moveout");
  }
  clearVal(event) {
    this.newVal = null;
  }
  users = [];
  override ngOnDestroy(): void {
    this.data;
    this.settings
    this.id;
    this.operatorID;
    this.currentDate;
    this.operatorUser;
    this.autoUserInfo;
    this.parsedChatFlowMessages;
    this.chatData;
    localStorage.removeItem('custIdEngaged');
    localStorage.removeItem('livechatCustomer');
    this.newChat$.unsubscribe();
  }

  handleFilterOperators(event) {
    let val = event.target?.value;
    if (val) {
      this.users = this.data?.user.filter(e => e.name.includes(val) || e.email.includes(val))
    } else {
      this.users = this.data.user;
    }
  }
  @HostListener('window:beforeunload', ['$event'])
  beforeunloadHandler(event: Event) {
    localStorage.removeItem('custIdEngaged');
    localStorage.removeItem('livechatCustomer');
  }
}
