import { NgClass, CommonModule } from '@angular/common';
import { Component, ElementRef, ViewChild } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { Router, ActivatedRoute, RouterLink } from '@angular/router';
import { TranslatePipe } from '@ngx-translate/core';
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 { LoaderService } from '../../../shared/services/loader.service';
import { TranslationService } from '../../../shared/services/translation.service';
import { CustomersService } from '../../../shared/services/customers/customers.service';
import html2pdf from 'html2pdf.js'; 
import { NgxPrintElementDirective, NgxPrintElementService } from 'ngx-print-element';
@Component({
  selector: 'app-custom-invoice',
  standalone: true,
  imports: [NgClass, TranslatePipes, FormsModule, CommonModule, RouterLink, NgxPrintElementDirective],
  templateUrl: './custom-invoice.component.html',
  styleUrl: './custom-invoice.component.scss'
})
export class CustomerCustomInvoiceComponent extends Unsub {
  public sendingResponse: { [key: string]: boolean } = {};
    @ViewChild('tableRef') tableElement!: ElementRef<HTMLTableElement>;
  transaction;
  customer;
  pathname;
  setting;
  admin;
  permission;
  usersymbol;
  usercurrency;
  subTotal = 0;
  url = "";
  id;
  constructor(
    private customersService: CustomersService,
    public print: NgxPrintElementService,
    private toastr: ToastrService, private router: Router,
    private translate: TranslatePipe,
    private activeRoute: ActivatedRoute,
    private translationService: TranslationService,
    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);
  }
  ngOnInit(): void {
    this.activeRoute.paramMap.pipe(takeUntil(this.unSubscribe$)).subscribe({
      next: (params) => {
        this.id = params.get('id');
        this.pathname = this.router.url;
        this.allProjects(this.id);
      },
    });
    this.url = location.origin + document.querySelector('base')?.getAttribute('href');
  }
  allProjects(id) {
    this.loaderService.showLoader();
    this.customersService
      .customInvoice(id)
      .pipe(takeUntil(this.unSubscribe$))
      .subscribe({
        next:
          (res) => {
            this.permission = res.permissions;
            this.transaction = res.transaction;
            this.customer = res.customer;
            this.setting = res.setting;
            this.admin = res.admin;
            this.usersymbol = res.usersymbol;
            this.usercurrency = res.usercurrency;
            this.loaderService.hideLoader();

            this.transaction?.custom_invoice_elements?.map(e => {
              this.subTotal += (e.price * e.quantity);
            })
          },
        error: () => {
          this.loaderService.hideLoader()
        },
      }
      );
  }

  getCurrencyPerTicket = (price) => {
    let final = '';
    const total = (Number(price) * Number(this.usercurrency?.conversion_factor)).toFixed(2);
    if (this.usercurrency?.position == 'Prefix') {
      final = this.usersymbol + '' + total;
    } else {
      final = total + '' + this.usersymbol;
    }
    return final;
  }

  // In your component.ts
  getTransactionStatus(transaction: any): string {
    switch (transaction?.status) {
      case 'completed':
      case 'paid':
        return this.translate.transform('Paid');
      case 'failed':
        return this.translate.transform('Failed');
      case 'refunded':
        return this.translate.transform('Refunded');
      case 'refundpending':
        return this.translate.transform('Refund Requested');
      case 'refundRejected':
        return this.translate.transform('Refund Rejected');
      case 'cancelled':
        return this.translate.transform('Invoice Cancelled');
      default:
        return this.translate.transform('Pending');
    }

  }
  // In your component.ts
  getTransactionStatusClass(transaction: any): string {
    let statusClass = 'p-2 px-4 fs-14 rounded-2 mb-0 text-white';

    switch (transaction?.status) {
      case 'completed':
      case 'paid':
        statusClass += ' bg-success';
        break;
      case 'failed':
        statusClass += ' bg-danger';
        break;
      case 'refunded':
        statusClass += ' bg-warning';
        break;
      case 'refundpending':
        statusClass += ' bg-secondary';
        break;
      case 'refundRejected':
        statusClass += ' bg-danger';
        break;
      case 'cancelled':
        statusClass += ' bg-danger';
        break;
      default:
        statusClass += ' bg-info';
        break;
    }

    return statusClass;
  }
  downloadPDF(): void {
    const element = document.getElementById('invoice');
    const options = {
      margin: 0.5,
      filename: 'invoice.pdf',
      image: { type: 'jpeg', quality: 0.98 },
      html2canvas: { scale: 2 },
      jsPDF: { unit: 'in', format: 'letter', orientation: 'portrait' }
    };

    if (element) {
      html2pdf().set(options).from(element).save();
    }
  }

  printCustomerTicketView(el: ElementRef<HTMLTableElement | HTMLElement>) {
    this.print.print(el).subscribe({
      next: () => {
      }
    })
  }

}
