import { DatePipe } from '@angular/common';
import { ChangeDetectorRef, Component, ElementRef, ViewChild } from '@angular/core';
import { FormBuilder } from '@angular/forms';
import { DomSanitizer } from '@angular/platform-browser';
import { ActivatedRoute, Router } from '@angular/router';
import { TranslatePipe } from '@ngx-translate/core';
import { CookieService } from 'ngx-cookie-service';
import { ToastrService } from 'ngx-toastr';
import { takeUntil } from 'rxjs';
import { Unsub } from '../../../../shared/class/unsub.class';
import { TranslatePipes } from '../../../../shared/pipes/translate/translate.pipe';
import { AdminService } from '../../../../shared/services/admin/admin.service';
import { CustomersService } from '../../../../shared/services/customers/customers.service';
import { LoaderService } from '../../../../shared/services/loader.service';
import { AdminPageHeaderComponent } from '../../../../shared/common/pageheader/admin-page-header/admin-page-header.component';
import Swal from 'sweetalert2';

@Component({
  selector: 'app-refund-view',
  standalone: true,
  imports: [TranslatePipes, DatePipe, AdminPageHeaderComponent],
  templateUrl: './refund-view.component.html',
  styleUrl: './refund-view.component.scss'
})
export class RefundViewComponent extends Unsub {

  @ViewChild('refundComment') refundComment!: ElementRef<HTMLTextAreaElement>;

  url = "";
  refundItem;
  timezone;
  setting;
  id;
  pageCount;

  constructor(
    private customerService: CustomersService,
    private toastr: ToastrService,
    private activatedRoute: ActivatedRoute,
    public fb: FormBuilder,
    private cdr: ChangeDetectorRef,
    private router: Router,
    private adminService: AdminService,
    private cookieService: CookieService,
    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);

    this.activatedRoute.paramMap.pipe(
      takeUntil(this.unSubscribe$)
    ).subscribe({
      next: (params) => {
        this.id = params.get('id');
        this.getTicketDetails(this.id);
      },
    });
    this.url = location.origin + document.querySelector('base')?.getAttribute('href');
  }

  ngOnInit(): void {
    this.adminService.RefreshRquestAdmin$.pipe(
      takeUntil(this.unSubscribe$)
    ).subscribe({
      next: () => {
        if (this.id) {
          this.pageCount = 1;
          this.getTicketDetails(this.id);
        }
      },
    });
  }
  getTicketDetails(id) {
    this.loaderService.showLoader();
    this.adminService.refundRequest(id).pipe(
      takeUntil(this.unSubscribe$)
    ).subscribe({
      next: (res) => {

        this.refundItem = res.refundItem;
        this.setting = res.setting;
        this.timezone = res.timezonedata;

        this.loaderService.hideLoader();
        // Trigger change detection manually
        this.cdr.detectChanges();
      },
      error: () => this.loaderService.hideLoader()
    });
  }
  handleSubmit() {
    if (this.value.trim() === '') {
      this.toastr.error(this.translate.transform("Comment cannot be empty"));
      return;
    }
    let data = {
      data: {
        id: this.id,
        commentReply: this.value
      }
    }
    this.adminService.refundRequestspostComment(data).subscribe({
      next: res => {
        if (res.success) {
          this.value = '';
          this.refundComment.nativeElement.value = "";
        }
        if (res.error) {
          this.toastr.error(this.translate.transform(res.error));
        }
      },
    })
  }
  value = "";
  handleCommentChange(event) {
    this.value = event.target.value;
  }

  approveRefund() {

    Swal.fire({
      icon: 'warning',
      title: this.translate.transform('Are you sure you want to approve refund!'),
      text: this.translate.transform('You won’t be able to revert this'),
      showCancelButton: true,
      confirmButtonColor: '#6259ca',
      cancelButtonColor: '#f11541',
      confirmButtonText: this.translate.transform('Okay'),
      cancelButtonText: this.translate.transform('Close'),
      reverseButtons: true,
    }).then((result: any) => {
      if (result.isConfirmed) {
        this.adminService
          .refundRequestsapprove({data: {id : this.id}})
          .pipe(takeUntil(this.unSubscribe$))
          .subscribe({
            next: (res) => {
              if (res?.success) {
                this.toastr.success(this.translate.transform(res.success));
              }
            },
          });
      }
    });
  }
  rejectRefund() {

    Swal.fire({
      icon: 'warning',
      title: this.translate.transform('Are you sure you want to reject refund?'),
      text: this.translate.transform('You won’t be able to revert this!'),
      showCancelButton: true,
      confirmButtonColor: '#6259ca',
      cancelButtonColor: '#f11541',
      confirmButtonText: this.translate.transform('Okay'),
      cancelButtonText: this.translate.transform('Close'),
      reverseButtons: true,
    }).then((result: any) => {
      if (result.isConfirmed) {
        this.adminService
          .refundRequestsreject({data:{id: this.id}})
          .pipe(takeUntil(this.unSubscribe$))
          .subscribe({
            next: (res) => {
              if (res?.success) {
                this.toastr.success(this.translate.transform(res.success));
              }
            },
          });
      }
    });
  }
}
