import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute, Router, RouterLink } from '@angular/router';
import { Observable, of, takeUntil } from 'rxjs';
import { NgbAlertModule, NgbDropdownModule, NgbModal, NgbPopoverModule, NgbTooltipModule } from '@ng-bootstrap/ng-bootstrap';
import { ToastrService } from 'ngx-toastr';
import Swal from 'sweetalert2';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
import { TranslatePipe } from '@ngx-translate/core';
import { Unsub } from '../../../shared/class/unsub.class';
import { AdminService } from '../../../shared/services/admin/admin.service';
import { GuestService } from '../../../shared/services/guest.service';
import { LoaderService } from '../../../shared/services/loader.service';
import { CommonModule } from '@angular/common';
import { TicketinfooterComponent } from './ticketinfooter/ticketinfooter.component';
import { TicketinfoComponent } from './ticketinfo/ticketinfo.component';
import { ShowticketincludeComponent } from './showticketinclude/showticketinclude.component';
import { ConversationsComponent } from './conversations/conversations.component';
import { DateAgoPipe } from '../../../shared/pipes/date-ago/date-ago.pipe';
import { TranslatePipes } from '../../../shared/pipes/translate/translate.pipe';
import { FormsModule } from '@angular/forms';
import { SharedModule } from '../../../shared/shared.module';
import { CanComponentDeactivate } from '../../../shared/guard/CanDeactivateGuard.guard';
import { NgSelectModule } from '@ng-select/ng-select';
@Component({
  selector: 'app-ticket-view',
  templateUrl: './ticket-view.component.html',
  styleUrls: ['./ticket-view.component.scss'],
  standalone: true,
  imports: [CommonModule, DateAgoPipe, TranslatePipes, TicketinfooterComponent, TicketinfoComponent, ShowticketincludeComponent, ConversationsComponent, NgbTooltipModule, NgbPopoverModule, RouterLink, NgbAlertModule, NgbDropdownModule, FormsModule, SharedModule, NgSelectModule]
})
export class TicketViewComponent extends Unsub implements OnInit, CanComponentDeactivate {
  @ViewChild('custmermismatch', { static: false }) 'custmermismatch'!: ElementRef;
  @ViewChild('commentsClose') commentsClose!: ElementRef;
  public ticketData!: any;
  public employIsWorking = false;
  public comment!: any;
  languages: any;
  // public getMedia: any = [];
  public doc: any;
  public sendingResponse: { [key: string]: boolean } = {};
  setting;
  timezone;
  now = new Date();
  notAssigncondition = false;
  id;
  user;
  permission: any;
  customername: any;
  private intersectionObserver!: IntersectionObserver;
  public isLoadingComments: boolean = false;
  totalcomments: number = 0;
  constructor(
    private adminService: AdminService,
    private activeRoute: ActivatedRoute,
    private modalService: NgbModal,
    private toastr: ToastrService,
    private guestService: GuestService,
    private router: Router,
    private translate: TranslatePipe,
    loaderService: LoaderService,
    private sanitizer: DomSanitizer
  ) {
    /**
    * This code calls the constructor of the parent class in a subclass. 
    * The super() function is used to initialize the parent class and allows access to its properties and methods. 
    * By calling  super(), the subclass can inherit and use the functionality of the parent class.
    **/
    super(loaderService);
    //used to get the param of id from url and assign the data to the user
    this.activeRoute.paramMap.pipe(takeUntil(this.unSubscribe$)).subscribe({
      next: (params) => {
        this.id = params.get('id');
        this.viewTicket();
      },
    });
    this.adminService.RefreshRquestAdmin$.pipe(
      takeUntil(this.unSubscribe$)
    ).subscribe({
      next: () => {
        this.pageCount = 1;
        this.viewTicket();
      },
    });
  }

  ngOnInit(): void {

  }

  viewTicket() {
    this.loaderService.showLoader();
    this.adminService
      .showTicket(this.id, 1, 10)
      .pipe(takeUntil(this.unSubscribe$))
      .subscribe({
        next: (ele: any) => {
          if (ele?.noticket) {
            this.router.navigate(['/admin/dashboard']);
            this.toastr.error(this.translate.transform(ele.noticket));
          } else {

            if (!ele?.allowreply) {
              this.router.navigate(['/restricted']);
            }
            this.user = ele.user;
            this.permission = ele.permissions;
            this.languages = Object.keys(ele.languages).map(key => ({ id: key, name: ele.languages[key] }));
            
            this.ticketData = ele;
            this.setting = ele.setting?.original;
            this.timezone = ele.timezonedata;

            this.comment = ele.comments.data;
            this.totalcomments = ele.comments.total;
            this.pageCount = ele.comments.current_page + 1;
            const toassignusers = ele?.ticket?.ticketassignmutliples;
            this.customername = ele?.ticket.cust.username;
            if (ele?.ticket.purchasecode != null && ele?.ticket.purchasecode != 'undefined') {
              this.verifyUserTicket(ele?.ticket?.purchasecode);
            }
            toassignusers?.forEach((element) => {
              if (element?.toassignuser_id == this.user?.id) {
                this.notAssigncondition = true;
              }
            });

          }
          this.loaderService.hideLoader();
        },
        error: () => this.loaderService.hideLoader()
      });
  }

  createnote(content) {
    const modalRef = this.modalService.open(content, { backdrop: 'static', keyboard: false });
    modalRef.result.then(
      () => {
      },
      () => {
      }
    );
  }
  open(content, link) {
    this.doc = link;
    const modalRef = this.modalService.open(content, { backdrop: 'static', keyboard: false });
    modalRef.result.then(
      () => {
        this.doc = '';
      },
      () => {
        this.doc = '';
      }
    );
  }
  createNote(ngForm, buttonId) {
    if (ngForm.valid) {
      this.sendingResponse[buttonId] = true;
      const data = ngForm.value;
      data['ticket_id'] = this.ticketData?.ticket?.id;

      this.adminService.createNote(data).pipe(takeUntil(this.unSubscribe$)).subscribe({
        next: (res) => {
          this.sendingResponse[buttonId] = false;
          if (res?.success) {
            this.toastr.success(this.translate.transform(res.success));
            this.modalService.dismissAll();
          }
          if (res?.error) {
            this.toastr.error(this.translate.transform(res.error));
          }
        },
        error: () => {
          this.sendingResponse[buttonId] = false;
        },
      });
    }
  }
  deleteNote(id, buttonId) {
    Swal.fire({
      icon: 'warning',
      title: this.translate.transform('Are You Sure You Want to Delete This Ticket Note?'),
      text: this.translate.transform('Warning: Deleting this Note Cannot Be Undone'),
      showCancelButton: true,
      confirmButtonColor: '#6259ca',
      cancelButtonColor: '#f11541',
      confirmButtonText: this.translate.transform('Yes, delete it!'),
      cancelButtonText: this.translate.transform('Close'),
      reverseButtons: true,
    }).then((result: any) => {
      if (result.isConfirmed) {
        const data = {
        };
        this.sendingResponse[buttonId] = true;
        this.adminService.deleteNote(id, data).pipe(takeUntil(this.unSubscribe$)).subscribe({
          next: (res) => {
            this.sendingResponse[buttonId] = false;
            if (res?.success) {
              this.toastr.success(this.translate.transform(res.success));
              this.modalService.dismissAll();
            }
            if (res?.error) {
              this.toastr.error(this.translate.transform(res.error));
            }
          },
          error: () => {
            this.sendingResponse[buttonId] = false;
          },
        });
      }
    });
  }
  deleteViolation(id, buttonId) {
    Swal.fire({
      icon: 'warning',
      title: this.translate.transform('Are You Sure You Want to Delete This Ticket violation Note?'),
      text: this.translate.transform('Warning: Deleting this Note Cannot Be Undone'),
      showCancelButton: true,
      confirmButtonColor: '#6259ca',
      cancelButtonColor: '#f11541',
      confirmButtonText: this.translate.transform('Yes, delete it!'),
      cancelButtonText: this.translate.transform('Close'),
      reverseButtons: true,
    }).then((result: any) => {
      if (result.isConfirmed) {
        const data = {
        };
        this.sendingResponse[buttonId] = true;
        this.adminService.deleteViolation(id, data).pipe(takeUntil(this.unSubscribe$)).subscribe({
          next: (res) => {
            this.sendingResponse[buttonId] = false;
            if (res?.success) {
              this.toastr.success(this.translate.transform(res.success));
              this.modalService.dismissAll();
            }
            if (res?.error) {
              this.toastr.error(this.translate.transform(res.error));
            }
          },
          error: () => {
            this.sendingResponse[buttonId] = false;
          },
        });
      }
    });
  }
  // ticketlicenseverify
  purchasedata = "";
  verifyTicket(ticketData, content) {
    const modalRef = this.modalService.open(content, { backdrop: 'static', keyboard: false });
    modalRef.result.then(
      () => { },
      () => { }
    );
    const data = {
      "envatopurchase_id": ticketData,
    };
    this.adminService.ticketlicenseverify(data).pipe(takeUntil(this.unSubscribe$)).subscribe({
      next: (res) => {
        this.purchasedata = res.output;
      },
    });
  }

  verifyUserTicket(ticketData) {
    const data = {
      "envatopurchase_id": ticketData,
    };
    this.adminService.ticketuserlicenseverify(data).pipe(takeUntil(this.unSubscribe$)).subscribe({
      next: (res) => {
        if (res?.client?.trim() === this.customername?.trim()) {
          this.custmermismatch?.nativeElement.classList.add('d-none');
        } else {
          this.custmermismatch?.nativeElement.classList.remove('d-none');
        }
      },
    });
  }

  deleteTicket(id, buttonId) {
    const data = {

    };

    Swal.fire({
      icon: 'warning',
      title: this.translate.transform('Are you sure ?'),
      text: this.translate.transform('You want to delete this Ticket!'),
      showCancelButton: true,
      confirmButtonColor: '#6259ca',
      cancelButtonColor: '#f11541',
      confirmButtonText: this.translate.transform('Yes, delete it!'),
      cancelButtonText: this.translate.transform('Close'),
      reverseButtons: true,
    }).then((result: any) => {
      if (result.isConfirmed) {
        this.sendingResponse[buttonId] = true;
        this.adminService.deleteTicket(id, data).pipe(takeUntil(this.unSubscribe$)).subscribe({
          next: (res) => {
            this.sendingResponse[buttonId] = false;
            if (res?.success) {
              this.router.navigate(['/admin/dashboard']);
              this.modalService.dismissAll();
              this.toastr.success(this.translate.transform(res.success));
            }
            if (res.error) {
              this.toastr.error(this.translate.transform(res.error));
            }
          },
          error: () => {
            this.sendingResponse[buttonId] = false;
          },
        });
      }
    })
  }
  forceClose(id, buttonId) {
    const data = {

    };

    Swal.fire({
      icon: 'warning',
      title: this.translate.transform('Are you sure ?'),
      text: this.translate.transform('You want to close this Ticket!'),
      showCancelButton: true,
      confirmButtonColor: '#6259ca',
      cancelButtonColor: '#f11541',
      confirmButtonText: this.translate.transform('Yes, close it!'),
      cancelButtonText: this.translate.transform('Close'),
      reverseButtons: true,
    }).then((result: any) => {
      if (result.isConfirmed) {
        this.sendingResponse[buttonId] = true;
        this.adminService.forceClose(id, data).pipe(takeUntil(this.unSubscribe$)).subscribe({
          next: (res) => {
            this.sendingResponse[buttonId] = false;
            if (res?.success) {
              this.toastr.success(this.translate.transform(res.success));
            }
            if (res.error) {
              this.toastr.error(this.translate.transform(res.error));
            }
          },
          error: () => {
            this.sendingResponse[buttonId] = false;
          },
        });
      }
    })
  }


  voilating(ngForm, buttonId) {
    const data = {};
    data["ticket_id"] = this.ticket_id;
    data["ticketviolation"] = ngForm.value.ticketviolation;
    if (this.ticket_violation_id) {
      data["ticket_violation_id"] = this.ticket_violation_id;
    }
    this.adminService.voilating(data).pipe(takeUntil(this.unSubscribe$)).subscribe({
      next: (res) => {
        this.violation = '';
        this.ticket_violation_id = ''
        if (res?.success) {
          this.toastr.success(this.translate.transform(res.success));
        }
        if (res.error) {
          this.toastr.error(this.translate.transform(res.error));
        }
      }
    });
  }
  ticket_id = "";
  violation = "";
  ticket_violation_id = "";
  violationModelFn(content, violation?) {
    const modalRef = this.modalService.open(content, { backdrop: 'static', keyboard: false });
    modalRef.result.then(
      () => {
      },
      () => {
      }
    );
    this.ticket_id = this.ticketData.ticket.id;
    this.violation = violation?.ticketviolation;
    this.ticket_violation_id = violation?.id;
  }

  tickettoarticle(id) {
    const ticketToArticleId: any[] = [];
    const tickettoarticle = document.querySelectorAll('.tickettoarticle');

    if (tickettoarticle?.length) {
      tickettoarticle.forEach((e: any) => {
        if (e.checked) {
          const val = e.getAttribute('value');
          ticketToArticleId.push(val);
        }
      });
    }
    if (ticketToArticleId?.length) {
      this.router.navigate([`/admin/knowledge/ticket-articles/${id}/${ticketToArticleId}`]);
    } else {
      this.toastr.error(this.translate.transform('Please select the field'));
    }
  }

  wrongcustomer(id) {
    const data = {
      id: id
    };
    this.adminService.wrongcustomer(data).pipe(takeUntil(this.unSubscribe$)).subscribe({
      next: res => {
        if (res?.success) {
          this.toastr.success(this.translate.transform(res.success));
        }
      }
    });
    // wrongcustomer
  }
  purchasverified(id) {
    const data = {
      id: id
    };
    this.adminService.purchasedetailsverify(data).pipe(takeUntil(this.unSubscribe$)).subscribe({
      next: res => {
        if (res?.success) {
          this.toastr.success(this.translate.transform(res.success));
        }
      }
    });
  }
  ngAfterViewInit() {
    this.intersectionObserver = new IntersectionObserver((entries) => {
      if (entries[0].isIntersecting && !this.isLoadingComments && this.comment?.length < this.totalcomments) {
        this.loadComments();
        this.isLoadingComments = true;
      }
    }, { threshold: 0 });
    const myElement = this.commentsClose.nativeElement;
    this.intersectionObserver.observe(myElement);
  }
  pageCount;

  loadComments() {
    // this.isloader = true;
    this.adminService.showTicket(this?.id, this.pageCount, 10)
      .subscribe((data: any) => {
        this.isLoadingComments = false;
        this.pageCount = data.comments.current_page + 1;
        this.comment = [...this.comment, ...data.comments.data];
      });
  }

  override ngOnDestroy() {
    this.modalService?.dismissAll();
    if (this.intersectionObserver) {
      this.intersectionObserver.disconnect();
    }
  }
  sanitizeHtml(html: string): SafeHtml {
    return this.sanitizer.bypassSecurityTrustHtml(html);
  }

  downloadFile(id, image) {
    this.guestService.image(id, image).subscribe({
      next: (res: Blob) => {
        const blobUrl = window.URL.createObjectURL(res);
        const link = document.createElement('a');
        link.href = blobUrl;
        link.setAttribute('download', image); // Set a default filename, customize as needed
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(blobUrl);
      }
    })
  }
  emailtoticketdownload(id, image) {
    this.guestService.emailtoticketdownload(id, image).subscribe({
      next: (res: Blob) => {
        const blobUrl = window.URL.createObjectURL(res);
        const link = document.createElement('a');
        link.href = blobUrl;
        link.setAttribute('download', image); // Set a default filename, customize as needed
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(blobUrl);
      }
    })
  }
  onemployIsWorking(value: boolean) {
    this.employIsWorking = value;
  }

  canDeactivate(): Observable<boolean> {
    if (this.employIsWorking) {
      const confirmLeave = confirm('You have unsaved changes. Do you really want to leave?');
      if (confirmLeave) {
        // Make API call before leaving if "Yes" is clicked
        this.makeApiCall();
        return of(true); // Allow navigation
      } else {
        return of(false); // Prevent navigation
      }
    }
    return of(true); // Allow navigation if no unsaved changes
  }

  makeApiCall(): void {
    const post = {
      userID: this.user.id,
      ticketId: this.ticketData?.ticket?.id,
    };

    this.adminService.employeesreplyingremove(post).subscribe({
      next: (response) => {},
      error: (err) => console.error('API call failed:', err),
    });
  }
  
  textToTranslate;
  translateModel(content) {
    this.textToTranslate = this.ticketData?.ticket?.message;
    this.modalService.open(content, { backdrop: 'static', keyboard: false, size: 'lg' });
  }

  translateFn(ngForm, buttonId) {
    if (ngForm.valid) {
      this.sendingResponse[buttonId] = true;
      let data = {
        text: this.textToTranslate,
        title: this.ticketData.ticket.subject,
        target_lang: ngForm.value.languages,
        user: 'employee',
      }
      this.adminService.translate(data).pipe(takeUntil(this.unSubscribe$)).subscribe({
        next:
          (res) => {
            this.sendingResponse[buttonId] = false;
            if (res.success) {
              this.toastr.success(this.translate.transform(res.success));
              this.modalService.dismissAll();
              this.ticketData.ticket.message = res.translated_text;
              this.ticketData.ticket.subject = res.translated_title;
            }
            if (res.message) {
              this.toastr.error(this.translate.transform('Translation failed: ' + res.message));
            }
            if (res?.error?.errors) {
              for (const el in res.error.errors) {
                this.toastr.error(this.translate.transform(res.error.errors[el]));
              }
            }
            else if (res.errors) {
              // Iterate through each error key (e.g., subcategoryname)
              Object.keys(res.errors).forEach(key => {
                // If there are errors for that key, display them
                res.errors[key].forEach((error: string) => {
                  this.toastr.error(this.translate.transform(error));
                });
              });
            }
          },
        error: () => {
          this.sendingResponse[buttonId] = false;
        },
      }
      );
    }
  }
}

