import React from "react";
import ExpenseSearch from "./ExpenseSearch";
import ExpenseSearchLoading from "./ExpenseSearchLoading";
import { fetchProjectExpenses } from "@/app/api/projectExpenses";
import dayjs from "dayjs";
import arraySupport from "dayjs/plugin/arraySupport";
import { OUTPUT_DATE_FORMAT, OUTPUT_TIME_FORMAT } from "@/app/utils/formatUtil";
import { fetchUserStaff } from "@/app/utils/fetchUtil";
import { fetchProjects } from "@/app/api/projects";


interface SubComponents {
  Loading: typeof ExpenseSearchLoading;
}
dayjs.extend(arraySupport)

const ExpenseSearchWrapper: React.FC & SubComponents = async () => {
  const [
    expenses,
    projects
  ] = await Promise.all([
    fetchProjectExpenses(),
    fetchProjects(),
  ]);
  const userStaff = await fetchUserStaff()
  const teamId = userStaff?.teamId

  let filteredExpenses = expenses
  if (teamId) {
    filteredExpenses = expenses.filter(e => e.teamId === teamId)
    if (userStaff.isTeamLead == false) {
      filteredExpenses = expenses
    }
  } 
  // else {
  //   filteredExpenses = []
  // }

  const _expenses = filteredExpenses.map((e) => {
    const formattedIssueDate = dayjs([e.issueDate[0], e.issueDate[1], e.issueDate[2]].join()).format(OUTPUT_DATE_FORMAT)
    let formattedReceiptDate = ""
    if (e.receiptDate) {
      formattedReceiptDate = dayjs([e.receiptDate[0], e.receiptDate[1], e.receiptDate[2]].join()).format(OUTPUT_DATE_FORMAT)
    }
    return ({
      ...e,
      issuedDate: e.issueDate,
      issueDate: formattedIssueDate,
      receiptDate: formattedReceiptDate,
      team: `${e.teamCode} - ${e.teamName}`
    })
  })
  return <ExpenseSearch 
    expenses={_expenses}
    projects={projects}
  />
  
};

ExpenseSearchWrapper.Loading = ExpenseSearchLoading;

export default ExpenseSearchWrapper;
