import { ChangeDetectionStrategy, ChangeDetectorRef, Component, ElementRef, EventEmitter, Input, Output, QueryList, Renderer2, SimpleChanges, ViewChild, ViewChildren } from '@angular/core';
import { FormControl, FormGroup, FormsModule, ReactiveFormsModule } from '@angular/forms';
import { SharedModule } from '../../../../../shared/shared.module';
import { CommonModule, Location } from '@angular/common';
import { NgbDropdownModule, NgbModal, NgbModalModule, NgbTooltipModule } from '@ng-bootstrap/ng-bootstrap';
import { ActivatedRoute, Router, RouterLink } from '@angular/router';
import { LiveChatService } from '../../../../../shared/services/admin/livechat.service';
import { ToastrModule, ToastrService } from 'ngx-toastr';
import Swal from 'sweetalert2';
import { TranslatePipe } from '@ngx-translate/core';
import { NgSelectInputComponent } from '../../../../../core/components/input/ng-select-input/ng-select-input.component';
import { DateAgoPipe } from '../../../../../shared/pipes/date-ago/date-ago.pipe';
import { TranslatePipes } from '../../../../../shared/pipes/translate/translate.pipe';
import { LivechatDataService } from '../../../../../shared/services/livechat-data.service';
import { Subscription, timer } from 'rxjs';

@Component({
  selector: 'app-live-chat-sidebar',
  standalone: true,
  imports: [CommonModule, FormsModule, DateAgoPipe, TranslatePipes, NgbTooltipModule, RouterLink, ReactiveFormsModule, ToastrModule, NgSelectInputComponent, NgbDropdownModule, NgbModalModule, NgSelectInputComponent],
  templateUrl: './live-chat-sidebar.component.html'
})
export class LiveChatSidebarComponent {
  @ViewChild('sidemenuList', { static: false }) sidemenuList!: ElementRef;
  @ViewChildren('liElement') liElements: QueryList<ElementRef>;
  @Input('data') data: any;
  @Input('settings') settings: any;
  @Input('timezone') timezone: any;
  @Input('id') id: any;
  @Input('link') link: any;
  @Input('operatorID') operatorID: any;
  @Input('AuthId') AuthId: any;
  typingEndSubscription: Subscription;
  custIdEngaged = null;
  @Output() sideMenuOpenClickFunction = new EventEmitter();
  constructor(private activatedRoute: ActivatedRoute, private liveChatDataService: LivechatDataService, private modalService: NgbModal, private liceChatService: LiveChatService, private toastr: ToastrService, private translate: TranslatePipe, private router: Router,
    private renderer: Renderer2, private cdr: ChangeDetectorRef) {
  }
  ngOnChanges(changes: SimpleChanges): void {
    //Called before any other lifecycle hook. Use it to inject dependencies, but avoid any serious work here.
    //Add '${implements OnChanges}' to the class.
    if (changes) {
      this.custIdEngaged = localStorage.getItem('custIdEngaged') ? JSON.parse(localStorage.getItem('custIdEngaged')) : null;

    }
  }
  ngOnInit() {

    this.liveChatDataService.data$.subscribe({
      next: res => {

        if (res.dataUpdate && this.data && this.router.url?.includes('new-chats')) {
          this.data = { ...this.data, filteredLiveCust: res.dataUpdate };
          this.cdr.markForCheck();
        }
        if (res.writing) {
          // Handle writing status res
          this.liElements?.forEach((li: ElementRef) => {
            if (li.nativeElement.getAttribute('data-id') == res.writing?.[0]?.id) {

              const messageElement = li.nativeElement.querySelector('.custrecentmessage');
              if (messageElement) {
                let users = ""
                if (res.writing?.length > 1) {
                  res.writing.map(e => {
                    users = users + e.userName + ','
                  })
                } else {
                  users = res.writing[0].userName;
                }
                this.renderer.setProperty(messageElement, 'textContent', users + ' Typing..');

                // Clear any existing timer
                if (this.typingEndSubscription) {
                  this.typingEndSubscription.unsubscribe();
                }

                // Set a timer to show "Typing Ended" after 5 seconds of no updates
                this.typingEndSubscription = timer(5000).subscribe(() => {
                  this.renderer.setProperty(messageElement, 'textContent', users + ' Typing Ended');
                  this.cdr.markForCheck(); // Inform Angular that it needs to check for changes
                });
                this.cdr.markForCheck(); // Inform Angular that it needs to check for changes
              }
            }
          });
          // Update your component state if needed
        }
      }
    })
  }
  reAssignUserFn(name, main) {
    if (name.valid) {
      let formData = new FormData();
      for (const key in name.value) {
        formData.append(key, name.value[key]);
      }
      formData.append("custId", this.assignId);
      this.liceChatService[main](formData).subscribe({
        next: res => {
          this.modalService.dismissAll();
          this.router.navigateByUrl('/admin/live-chat/new-chats')
        }
      })
    }
  }
  assignId;
  openAssignModel(content, id) {
    this.reAssign.controls['custId'].setValue(id);
    this.assignId = id;
    this.modalService.open(content)
  }
  conversationLeave(id) {
    this.liceChatService.livechatConversationleave(id).subscribe({
      next: res => {
        if (res?.success) {
          this.toastr.success(this.translate.transform(res.success));
        }
      }
    })
  }
  removeUserFromUnread(id) {
    this.liceChatService.livechatRemoveUserFromUnread(id).subscribe({
      next: res => {
        if (res?.success) {
          this.toastr.success(this.translate.transform(res.success));
        }
      }
    })
  }
  conversationUnread(id) {
    this.liceChatService.livechatConversationUnread(id).subscribe({
      next: res => {
        if (res?.success) {
          this.toastr.success(this.translate.transform(res.success));
        }
      }
    })
    localStorage.removeItem('livechatCustomer')
  }
  markAsSolved(id) {
    this.liceChatService.livechatMarkSolved(id).subscribe({
      next: res => {
        if (res?.success) {
          this.toastr.success(this.translate.transform(res.success));
          this.router.navigate([`/admin/live-chat/solved-chats`], { queryParams: { id: res?.id } })
        }
      }
    })
  }
  livechatConversationDelete(id) {

    Swal.fire({
      icon: 'warning',
      title: this.translate.transform('Are you sure you want to continue?'),
      text: this.translate.transform('This conversation will be deleted'),
      showCancelButton: true,
      confirmButtonColor: '#e64942',
      cancelButtonColor: '#f11541',
      confirmButtonText: this.translate.transform('Delete'),
      cancelButtonText: this.translate.transform('Cancle'),
      reverseButtons: true,
      customClass: {
        confirmButton: 'custom-confirm-button',
        cancelButton: 'custom-cancel-button',
      }
    }).then((result: any) => {
      if (result.isConfirmed) {
        this.liceChatService.livechatConversationDelete(id)
          // .pipe(takeUntil(this.unSubscribe$))
          .subscribe({
            next: (res) => {
              this.toastr.success(this.translate.transform('Chat Deleted'));
              // this.customerData = null
              // this.chatData = null
              // this.parsedChatFlowMessages = []
              // this.operatorUser = null;
            },
            error: () => {
            },
          });
      }
    });
  }

  reAssign = new FormGroup({
    'custId': new FormControl(null)
  });
  // SideBar and Online operators loop click
  singlecustdata(id) {
    localStorage.removeItem('custIdEngaged');
    this.sideMenuOpenClickFunction.emit(id);
    this.router.navigate([], {
      relativeTo: this.activatedRoute,
      queryParams: { id: id },
      queryParamsHandling: 'merge' // Merge with existing query params
    });
  }

}
