import { Component, OnInit, Input } from '@angular/core';
import { NgbDropdownModule, NgbModal, NgbModalModule, NgbPopoverModule, NgbTooltipModule } from '@ng-bootstrap/ng-bootstrap';
import { TranslatePipe } from '@ngx-translate/core';
import { ToastrService } from 'ngx-toastr';
import { takeUntil } from 'rxjs';
import { Unsub } from '../../../../shared/class/unsub.class';
import { AdminService } from '../../../../shared/services/admin/admin.service';
import { LoaderService } from '../../../../shared/services/loader.service';
import { CommonModule } from '@angular/common';
import { NgSelectModule } from '@ng-select/ng-select';
import { TranslatePipes } from '../../../../shared/pipes/translate/translate.pipe';
import { FormsModule } from '@angular/forms';
import { TimezonePipe } from '../../../../shared/pipes/timzone.pipe';
import Swal from 'sweetalert2';

@Component({
  selector: 'app-ticketinfooter',
  templateUrl: './ticketinfooter.component.html',
  styleUrls: ['./ticketinfooter.component.scss'],
  standalone: true,
  imports: [CommonModule, TranslatePipes, NgSelectModule, NgbTooltipModule, NgbPopoverModule, NgbDropdownModule, NgbModalModule, FormsModule, TimezonePipe]
})
export class TicketinfooterComponent extends Unsub implements OnInit {
  @Input() user: any; // decorate the property with @Input()
  @Input() permissions: any; // decorate the property with @Input()
  // @Input() ticketDataParent: any; // decorate the property with @Input()
  ticketDataParent: any;
  @Input()
  get data(): any {

    return this.ticketDataParent;
  }
  set data(value: any) {
    if (value) {
      this.ticketDataParent = value;
      this.subcategory = this.ticketDataParent?.ticket?.subcategoriess?.id
      this.projects = this.ticketDataParent?.ticket?.project
    }
  }
  public sendingResponse: { [key: string]: boolean } = {};
  ticketDetails;
  category = [];
  subcategory = [];
  envatoName;
  projects = null;
  userDetails;
  haspurchasecode = [];
  hassubcategoriess = [];
  hasproject = [];
  envatoId;
  constructor(
    private adminService: AdminService,
    private toastr: ToastrService,
    private modalService: NgbModal,
    private translate: TranslatePipe,
    loaderService: LoaderService
  ) {
    /**
    * 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);
  }

  priorityList: any[] = [
    { id: 1, name: 'Low' },
    { id: 2, name: 'Medium' },
    { id: 3, name: 'High' },
    { id: 4, name: 'Critical' },
  ];
  ngOnInit(): void {
    if (this.ticketDataParent?.setting?.original?.ENVATO_ON != 'on') {
      this.haspurchasecode = this.ticketDataParent?.ticket.purchasecode;
      if (this.haspurchasecode) {
        this.envatoStatus = false;
      }
    }
    this.licencekey = this.ticketDataParent?.ticket.purchasecode;
    this.hasproject = this.ticketDataParent?.projects;
    this.hassubcategoriess = this.ticketDataParent?.subcategory;
  }

  reopen(id, buttonId) {
    const data = {
      reopenid: id,

    };
    this.sendingResponse[buttonId] = true;
    this.adminService.reopenTicket(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;
      },
    });
  }
  assignedMem: any[] = [];
  AssignTicket(content: any, row: any) {
    this.category = this.ticketDataParent.category;
    this.ticketDetails = row;

    this.adminService.userListOtherAssign(row?.enc_id).pipe(takeUntil(this.unSubscribe$)).subscribe({
      next: (userlist: any) => {
        if (userlist && userlist.assign_data.ticketassignmutliples) {
          userlist.assign_data.ticketassignmutliples.map((list: any) => {
            this.assignedMem.push(list.toassignuser_id);
          });
        }
        this.userDetails = userlist;
        const modalRef = this.modalService.open(content, { backdrop: 'static', keyboard: false });
        modalRef.result.then(
          () => {
            this.assignedMem = [];
          },
          () => {
            this.assignedMem = [];
          }
        );
      }
    });
  }
  priorityModel(content: any) {
    const modalRef = this.modalService.open(content, { backdrop: 'static', keyboard: false });
    modalRef.result.then(
      () => {
      },
      () => {
      }
    );
  }
  categoryModel(content: any) {
    this.category = this.ticketDataParent.category;
    this.categorychange(this.ticketDataParent?.ticket?.category?.id);
    const modalRef = this.modalService.open(content, { backdrop: 'static', keyboard: false });
    modalRef.result.then(
      () => {
        this.category = [];
        this.projects = null;
        this.subcategory = [];
        this.haspurchasecode = [];
        this.envatoStatus = true;
        this.hasproject = [];
        this.hassubcategoriess = [];
        this.licencekey = '';
      },
      () => {
        this.category = []; this.projects = null;
        this.envatoStatus = true;
        this.subcategory = [];
        this.haspurchasecode = [];
        this.hasproject = [];
        this.hassubcategoriess = [];
        this.licencekey = '';
      }
    );
  }

  SelfAssign(row: any, buttonId) {
    this.sendingResponse[buttonId] = true;
    const data = {
      "assigned_id": row?.selfassignuser_id,
    };
    this.adminService.adminSelfAssign(row?.enc_id, data).pipe(takeUntil(this.unSubscribe$)).subscribe({
      next: (response) => {
        this.sendingResponse[buttonId] = false;
        if (response && response?.success) {
          this.toastr.success(this.translate.transform(response.success));
        }
      },
      error: () => {
        this.sendingResponse[buttonId] = false;
      },
    });
  }
  OtherAssign(event: any, buttonId) {
    const data = {
      "assigned_id": this.userDetails.assign_data?.id,
      "assigned_user_id": event.assigned_user_id,
    };

    this.sendingResponse[buttonId] = true;
    this.adminService.otherAssignTicket(data).pipe(takeUntil(this.unSubscribe$)).subscribe({
      next: (response) => {
        this.sendingResponse[buttonId] = false;
        if (response && response?.success) {
          this.toastr.success(this.translate.transform(response?.success));
          this.modalService.dismissAll();
          this.assignedMem = [];
        }
      },
      error: () => {
        this.sendingResponse[buttonId] = false;
      },
    });
  }

  categorychange(id) {
    this.subcategory = [];
    this.projects = null;
    this.licencekey = '';
    this.envatoName = '';
    const data = {
      "cat_id": id,
    };
    this.adminService.getCatagoryData(data).pipe(takeUntil(this.unSubscribe$)).subscribe({
      next: (res) => {
        this.subcategory = [];
        this.haspurchasecode = [];
        this.hasproject = [];
        this.hassubcategoriess = [];

        if (res.ENVATO_ON == 'on') {
          this.haspurchasecode = res.envatosuccess;
          this.envatoStatus = true;
        }
        this.hasproject = res.projects;
        this.hassubcategoriess = res.subcategories;
      },
    });
  }

  categoryFn(ngForm, buttonId) {
    if (ngForm.valid && this.envatoStatus) {
      const data = ngForm.value;
      data['envato_id'] = this.envatoId;
      data['ticket_id'] = this.ticketDataParent.ticket?.id;
      data['envato_support'] = this.licencesupport;

      this.sendingResponse[buttonId] = true;
      this.adminService.updateCategory(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;
        },
      });
    }
  }
  priorityFn(ngForm, buttonId) {
    const data = {
      "priority_id": this.ticketDataParent?.ticket?.id,
      "priority": ngForm.value.priority,
    };
    this.sendingResponse[buttonId] = true;

    this.adminService.priorityChange(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;
      },
    });
  }

  licencekey;
  envatoStatus = true;
  licencekeyStatus = false;
  licencesupport;
  envatoVerify(event, buttonId) {
    if (event.value?.trim()?.length >= 36) {
      this.envatoId = event.value.trim();
      const data = {
        data: event.value,
      };
      this.sendingResponse[buttonId] = true;
      this.adminService.envatoverify(data).pipe(takeUntil(this.unSubscribe$)).subscribe({
        next: (res) => {

          this.sendingResponse[buttonId] = false;
          if (res?.valid != 'true') {
            if (this.ticketDataParent?.setting?.original?.ENVATO_EXPIRED_BLOCK == 'on') {
              this.toastr.error(this.translate.transform(res.message));
              this.envatoStatus = false;
            }
            if (this.ticketDataParent?.setting?.original?.ENVATO_EXPIRED_BLOCK == 'off') {

              this.toastr.warning(this.translate.transform(res.message));
              this.envatoName = res.name;
              this.licencekey = res.key;
              this.licencekeyStatus = true;
              this.licencesupport = res.valid;
              this.envatoStatus = true;
            }
            if (res.message == "The Purchase Code is invalid.") {
              this.envatoStatus = false;
            }
          }
          if (res?.valid == 'true') {
            this.toastr.success(this.translate.transform(res.message));
            this.envatoName = res.name;
            this.licencekey = res.key;
            this.licencekeyStatus = true;
            this.licencesupport = res.valid;
            this.envatoStatus = true;
          }
        },
        error: () => {
          this.sendingResponse[buttonId] = false;
        },
      });
    }
  }
  unAssignSelf(id, buttonId) {
    this.sendingResponse[buttonId] = true;
    this.sendingResponse[buttonId] = true;
    this.adminService.unAssignlist(id).pipe(takeUntil(this.unSubscribe$)).subscribe({
      next: (res) => {
        this.sendingResponse[buttonId] = false;
        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;
      },
    });
  }

  ticketFileUploadPermission(event: Event, content): void {
    const target = <HTMLInputElement>event.target;
    if (!target?.checked) {
      Swal.fire({
        icon: 'warning',
        title: this.translate.transform('Are you sure you want to continue?'),
        text: this.translate.transform('This will delete file upload permission for this ticket'),
        showCancelButton: true,
        confirmButtonColor: '#6259ca',
        cancelButtonColor: '#f11541',
        confirmButtonText: this.translate.transform('Ok'),
        cancelButtonText: this.translate.transform('Cancel'),
        reverseButtons: true,
      }).then((result: any) => {
        if (result.isConfirmed) {
          let data = {
            id: this.ticketDataParent?.ticket?.id,
            permission: target?.checked,
            ticket_id: this.ticketDataParent?.ticket?.id,
          }
          this.adminService
            .fileuploadpermission(data)
            .pipe(takeUntil(this.unSubscribe$))
            .subscribe({
              next: (res) => {
                if (res?.success) {
                  this.toastr.success(this.translate.transform(res.success));
                }
              },
              error: () => {
              },
            });
        }else{
          target.checked = true;
        }
      });
    } else {
      const modalRef = this.modalService.open(content, { backdrop: 'static', keyboard: false, size: 'lg' });
      
      modalRef.result.then(
        () => {
          target.checked = false;
        },
        (res) => {
          if(res == 'Cross click'){
            target.checked = false;
          }
        },
    );
    }

  }

  filePermissionFn(ngForm, buttonId) {
    let data = {
      id: this.ticketDataParent?.ticket?.id,
      permission: ngForm.value.permission,
      ticket_id: this.ticketDataParent?.ticket?.id,
    }
    this.sendingResponse[buttonId] = true;

    this.adminService.fileuploadpermission(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;
      },
    });
  }
  override ngOnDestroy() {
    this.modalService?.dismissAll();
  }
}
