// 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, timestampToDateStringV2 } from "@/app/utils/formatUtil";
import { fetchTeam } from "@/app/api/team";
import { fetchUserAbilities, fetchUserStaff } from "@/app/utils/fetchUtil";
import { fetchProjects } from "@/app/api/projects";


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 userStaff = await fetchUserStaff()
  const teamId = userStaff?.teamId
  const invoices = await fetchInvoicesV3()
  const projects = await fetchProjects()

  let filteredInvoice = invoices
  if (teamId) {
    filteredInvoice = invoices.filter(i => i.teamId === teamId)
    if (userStaff.isTeamLead == false) {
      filteredInvoice = invoices
    }
  } 

  const convertedInvoices = filteredInvoice.map((invoice)=>{
    return{
      id: invoice.id,
      invoiceNo: invoice.invoiceNo,
      projectCode: invoice.projectCode,
      projectName: invoice.projectName,
      team: invoice.teamCodeName,
      teamCodeName: invoice.teamCodeName,
      issuedDate: timestampToDateStringV2(invoice.invoiceDate)!!,
      receiptDate: timestampToDateStringV2(invoice.receiptDate)!!,
      issuedAmount: invoice.issueAmount,
      receivedAmount: invoice.paidAmount,
      settled: invoice.paidAmount===null ? false : invoice.paidAmount === invoice.issueAmount
    }
  })

  const abilities = await fetchUserAbilities();

  return <InvoiceSearch 
    invoices={convertedInvoices}
    projects={projects}
    abilities={abilities}
  />
  
};

InvoiceSearchWrapper.Loading = InvoiceSearchLoading;

export default InvoiceSearchWrapper;
