import { Component, ElementRef, ViewChild } from '@angular/core';
import { SharedModule } from '../../../../shared/shared.module';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { ActivatedRoute, Router, RouterLink } from '@angular/router';
import { NgbDropdownModule, NgbModalModule, NgbTooltipModule } from '@ng-bootstrap/ng-bootstrap';
import { Subscription, takeUntil } from 'rxjs';
import { Unsub } from '../../../../shared/class/unsub.class';
import { AdminService } from '../../../../shared/services/admin/admin.service';
import { LiveChatService } from '../../../../shared/services/admin/livechat.service';
import { LoaderService } from '../../../../shared/services/loader.service';
import { NgSelectInputComponent } from '../../../../core/components/input/ng-select-input/ng-select-input.component';
import { CommonModule } from '@angular/common';
import { AgentMessageComponent } from '../chat-interface/agent-message/agent-message.component';
import { CommentMessageComponent } from '../chat-interface/comment-message/comment-message.component';
import { CustomerMessageComponent } from '../chat-interface/customer-message/customer-message.component';
import { FeedbackCommentComponent } from '../chat-interface/feedback-comment/feedback-comment.component';
import { NgSelectModule } from '@ng-select/ng-select';
import { TextareaInputComponent } from '../../../../core/components/input/textarea-input/textarea-input.component';
import { EmojiComponent } from '../chat-interface/emoji/emoji.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-my-opened-charts',
  standalone: true,
  imports: [CommonModule, FormsModule, ReactiveFormsModule, RouterLink, SharedModule, NgbDropdownModule, AgentMessageComponent, CustomerMessageComponent, CommentMessageComponent, FeedbackCommentComponent, NgSelectInputComponent, NgbModalModule, NgbTooltipModule, NgSelectModule, TextareaInputComponent, EmojiComponent, LivechatViewComponent, CustomerInfoComponent, LiveChatSidebarComponent, TranslatePipes, AdminPageHeaderComponent],
  templateUrl: './my-opened-charts.component.html',
  styleUrl: './my-opened-charts.component.scss'
})
export class MyOpenedChartsComponent extends Unsub {
  @ViewChild('supportexpired') supportexpired!: ElementRef;
  @ViewChild('verifysupportexpired') verifysupportexpired!: ElementRef;
  @ViewChild('chatReplyInput', {static: false}) chatReplyInput!:ElementRef;
  data;
  newVal = '';
  pastMessage = '';
  subscategory = null;
  reply = '';
  isChat = true;
  settings
  userRole
  id = null;
  timezone;
  currentDate;
  autoUserInfo;
  AuthId;
  customerData;
  parsedChatFlowMessages: any[] = [];
  chatData
  operatorUser: any = null;

  isConnected
  constructor(private liceChatService: LiveChatService, private adminService: AdminService, private activatedRoute: ActivatedRoute,  private liveChatDataService: LivechatDataService, private toastr: ToastrService,
      private translate: TranslatePipe,
    loaderService: LoaderService, 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.customerData = null
        this.chatData = null
        this.parsedChatFlowMessages = []
        this.operatorUser = null;
        this.id = params.id;
        this.openedChatFn();
        this.adminService.RefreshRquestAdmin$.pipe(
          takeUntil(this.unSubscribe$)
        ).subscribe({
          next: () => {
            this.openedChatFn();
          },
        });
      }
    })
  }
  
  myOpenedCaht$: Subscription;
  openedChatFn() {

    this.loaderService.showLoader();
    // this.isloader = true;
    this.myOpenedCaht$ = this.liceChatService.myopened()
      .subscribe({
        next: (res) => {
          this.AuthId = res.userId;let NewUserId = null;
          this.timezone = res.timezonedata;

          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){
            this.liveChatDataService.updateData(res.filteredLiveCust); 
            if(this.id != NewUserId){
              this.router.navigate([], {
                relativeTo: this.activatedRoute,
                queryParams: { id: res.filteredLiveCust?.[0]?.id },
                queryParamsHandling: 'merge' // Merge with existing query params
              });
            }
            this.data = res;
          }
          this.reply = '';
          this.newVal = '';
          this.settings = res.settings;
          if (this.id) {
            this.sideMenuOpenClickFunction(NewUserId);
          }
        }
      })
  }


  // SideBar and Online operators loop click
  sideMenuOpenClickFunction(id) {
    // let ele = event.currentTarget;
    // To Prevent the engage Conversation Btn
    // document.querySelector('.textareaDiv')?.classList.add('d-none')
    // document.querySelector('.engageConversation')?.classList.remove('d-none')

    this.liceChatService.singlecustdata(id).subscribe({
      next: data => {        
        this.chatData = data;
        this.customerData = data.livechatcust;
        this.liveChatDataService.updateConversationData(data)
        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
        if (document.querySelector(".chat-msg") && (document.querySelector(".chat-msg")?.classList.contains('font-weight-bold') || document.querySelector(".unReadIndexNumber"))) {
          document.querySelector(".chat-msg")?.classList.remove("font-weight-bold")
        }

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

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


        // To Scroll Down the Conversation
        document.querySelector("#operator-conversation")?.scrollBy(0, (document.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(res.message));
        }
      }
    })
  }
  clearVal(event){
    this.newVal = null;
  }
  override ngOnDestroy(): void {
    this.data;
    this.settings
    this.id;
    this.currentDate;
    this.operatorUser;
    this.autoUserInfo;
    this.parsedChatFlowMessages;
    this.chatData;
    localStorage.removeItem('custIdEngaged');
    this.myOpenedCaht$.unsubscribe();
  }

}
