// import { fetchInvoiceCategories, fetchInvoices } from "@/app/api/companys";
import React from "react";
import InvoiceSearch from "./InvoiceSearch";
import InvoiceSearchLoading from "./InvoiceSearchLoading";
import { fetchInvoicesV3, fetchIssuedInvoices, fetchReceivedInvoices, issuedInvoiceList, issuedInvoiceResult } from "@/app/api/invoices";
import { INPUT_DATE_FORMAT, convertDateArrayToString, convertDateToString, moneyFormatter, timestampToDateString } from "@/app/utils/formatUtil";


interface SubComponents {
  Loading: typeof InvoiceSearchLoading;
}

// function calculateHourlyRate(loweLimit: number, upperLimit: number, numOfWorkingDay: number, workingHour: number){
//   const hourlyRate = (loweLimit + upperLimit)/2/numOfWorkingDay/workingHour
//   return hourlyRate.toLocaleString()
// }

const InvoiceSearchWrapper: React.FC & SubComponents = async () => {
  const issuedInvoices = await fetchIssuedInvoices()
  const receivedInvoices = await fetchReceivedInvoices()
  const invoices = await fetchInvoicesV3()
  
  // console.log(invoices)

  const convertedIssedInvoices = issuedInvoices.map((invoice)=>{
    return{
      id: invoice.id,
      invoiceNo: invoice.invoiceNo,
      projectCode: invoice.projectCode,
      projectName: invoice.projectName,
      stage: invoice.stage,
      paymentMilestone: invoice.paymentMilestone,
      invoiceDate: convertDateArrayToString(invoice.invoiceDate, INPUT_DATE_FORMAT, false)!!,
      dueDate: convertDateArrayToString(invoice.dueDate, INPUT_DATE_FORMAT, false)!!,
      issuedAmount: moneyFormatter.format(invoice.issuedAmount)
    }
  })

  const convertedReceivedInvoices = receivedInvoices.map((invoice)=>{
    return{
      id: invoice.id,
      invoiceNo: invoice.invoiceNo,
      projectCode: invoice.projectCode,
      projectName: invoice.projectName,
      team: invoice.team,
      receiptDate: convertDateArrayToString(invoice.receiptDate, INPUT_DATE_FORMAT, false)!!,
      receivedAmount: moneyFormatter.format(invoice.receivedAmount)
    }
  })

  const convertedInvoices = invoices.map((invoice)=>{
    return{
      id: invoice.id,
      invoiceNo: invoice.invoiceNo,
      projectCode: invoice.projectCode,
      projectName: invoice.projectName,
      team: invoice.team,
      issuedDate: timestampToDateString(invoice.invoiceDate)!!,
      receiptDate: timestampToDateString(invoice.receiptDate??null)!!,
      issuedAmount: moneyFormatter.format(invoice.issueAmount),
      receivedAmount: invoice.paidAmount === null ? "-" : moneyFormatter.format(invoice.paidAmount)
    }
  })

  return <InvoiceSearch 
    issuedInvoice={convertedIssedInvoices} 
    receivedInvoice={convertedReceivedInvoices}
    invoices={convertedInvoices}
  />
  
};

InvoiceSearchWrapper.Loading = InvoiceSearchLoading;

export default InvoiceSearchWrapper;
