import { Component } from '@angular/core';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { TranslatePipe } from '@ngx-translate/core';
import { ToastrService } from 'ngx-toastr';
import { AdminService } from '../../../../shared/services/admin/admin.service';
import { LoaderService } from '../../../../shared/services/loader.service';
import { TranslationService } from '../../../../shared/services/translation.service';
import { Unsub } from '../../../../shared/class/unsub.class';
import { CommonModule, DatePipe, NgClass } from '@angular/common';
import { TranslatePipes } from '../../../../shared/pipes/translate/translate.pipe';
import { takeUntil } from 'rxjs';
import { ActivatedRoute, Router } from '@angular/router';
import { FormsModule } from '@angular/forms';
import Swal from 'sweetalert2';

@Component({
  selector: 'app-custom-invoice',
  standalone: true,
  imports: [NgClass, TranslatePipes, FormsModule, CommonModule],
  providers: [DatePipe],
  templateUrl: './custom-invoice.component.html',
  styleUrl: './custom-invoice.component.scss'
})
export class CustomInvoiceComponent extends Unsub {
  public sendingResponse: { [key: string]: boolean } = {};
  transaction;
  customer;
  pathname;
  setting;
  admin;
  symbol;
  permission;
  usersymbol;
  usercurrency;
  subTotal = 0;
  url = "";
  id;
  constructor(
    private adminService: AdminService,
    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);
    this.url = location.origin + document.querySelector('base')?.getAttribute('href');
  }
  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);
      },
    });
  }
  allProjects(id) {
    this.loaderService.showLoader();
    this.adminService
      .customInvoice(id)
      .pipe(takeUntil(this.unSubscribe$))
      .subscribe({
        next:
          (res) => {
            this.permission = res.permissions;
            this.transaction = res.transaction;
            this.customer = res.customer;
            this.symbol = res.symbol;
            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()
        },
      }
      );
  }


  cancleRequestFun(id, buttonId) {
    Swal.fire({
      icon: 'warning',
      title: this.translate.transform('Are you sure ?'),
      text: this.translate.transform('Your will not be able to recover!'),
      showCancelButton: true,
      confirmButtonColor: '#6259ca',
      cancelButtonColor: '#f11541',
      confirmButtonText: this.translate.transform('Yes, Cancel it!'),
      cancelButtonText: this.translate.transform('Close'),
      reverseButtons: true,
    }).then((result: any) => {
      if (result.isConfirmed) {
        this.sendingResponse[buttonId] = true;
        this.adminService
          .cancelInvoice(id)
          .pipe(takeUntil(this.unSubscribe$))
          .subscribe({
            next:
              (res) => {
                this.sendingResponse[buttonId] = false;
                if (res.success) {
                  this.toastr.success(this.translate.transform(res.success));
                  this.router.navigate(['/admin/payments/custom-invoices']);
                }
              },
            error: () => {
              this.sendingResponse[buttonId] = false;
            },
          }
          );
      }
    });
  }


  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;
  }

}
