"use client";
import * as React from "react";
import Grid from "@mui/material/Grid";
import { useState, useEffect, useMemo } from "react";
import Paper from "@mui/material/Paper";
import { TFunction } from "i18next";
import { useTranslation } from "react-i18next";
import { Card, CardHeader } from "@mui/material";
import CustomSearchForm from "../CustomSearchForm/CustomSearchForm";
import CustomDatagrid from "../CustomDatagrid/CustomDatagrid";
import ReactApexChart from "react-apexcharts";
import { ApexOptions } from "apexcharts";
import { GridColDef, GridRowSelectionModel } from "@mui/x-data-grid";
import ReportProblemIcon from "@mui/icons-material/ReportProblem";
import dynamic from "next/dynamic";
import "../../app/global.css";
import { AnyARecord, AnyCnameRecord } from "dns";
import SearchBox, { Criterion } from "../SearchBox";
import ProgressByClientSearch from "@/components/ProgressByClientSearch";
import { Suspense } from "react";
import { fetchFinancialSummaryCard } from "@/app/api/financialsummary";
import { exportFinancialSummaryByClientExcel, exportFinancialSummaryByProjectExcel, FinancialSummaryByProjectResult, FinancialSummaryByClientResult, searchFinancialSummaryByClient,searchFinancialSummaryByProject } from "@/app/api/financialsummary/actions";
import ProjectFinancialCard from "./ProjectFinancialCard";
import VisibilityIcon from '@mui/icons-material/Visibility';
import { downloadFile } from "@/app/utils/commonUtil";
import Typography from "@mui/material/Typography";
import { useRouter } from "next/navigation";

type SearchProjectQuery = Partial<Omit<FinancialSummaryByProjectResult, "id">>;
type SearchClientQuery = Partial<Omit<FinancialSummaryByClientResult, "id">>;
type SearchProjectParamNames = keyof SearchProjectQuery;
type SearchClientParamNames = keyof SearchClientQuery;

const ProjectFinancialSummary: React.FC = () => {
  const router = useRouter();
  const [SearchCriteria, setSearchCriteria] = React.useState({});
  const { t } = useTranslation("dashboard");
  const [selectionModel, setSelectionModel]: any[] = React.useState([]);
  const [projectFinancialData, setProjectFinancialData]: any[] = React.useState([]);
  const [clientFinancialRows, setClientFinancialRows]: any[] = React.useState([]);
  const [projectFinancialRows, setProjectFinancialRows]: any[] = React.useState([]);
  const [filteredProjectResult, setFilteredProjectResult]:any[] = useState([]);
  const [filteredClientResult, setFilteredClientResult]:any[] = useState([]);

  const projectSearchCriteria: Criterion<SearchProjectParamNames>[] = useMemo(
    () => [
      { label: t("Project Code"), paramName: "projectCode", type: "text" },
      { label: t("Project Name"), paramName: "projectName", type: "text" },
    ],
    [t],
  );
  const clientSearchCriteria: Criterion<SearchClientParamNames>[] = useMemo(
    () => [
      { label: t("Client Code"), paramName: "customerCode", type: "text" },
      { label: t("Client Name"), paramName: "customerName", type: "text" },
    ],
    [t],
  );

  const fetchData = async () => {
    const financialSummaryCard = await fetchFinancialSummaryCard();
    console.log(financialSummaryCard)
    setProjectFinancialData(financialSummaryCard)
  }
  const fetchTableData = async (teamId?:any) => {
    const financialSummaryByClient = await searchFinancialSummaryByClient(teamId);
    
    console.log(financialSummaryByClient)
    // console.log(financialSummaryByProject)
    setClientFinancialRows(financialSummaryByClient)
    setFilteredClientResult(financialSummaryByClient)
  }
  useEffect(() => {
    fetchData()
    // fetchTableData(undefined)
   }, []);

  const rows0 = [{id: 1,projectCode:"M1201",projectName:"Consultancy Project C", team:"XXX", teamLeader:"XXX", startDate:"01/08/2022", targetEndDate: "01/05/2024", client:"Client A", subsidiary:"N/A"},
  {id: 2,projectCode:"M1321",projectName:"Consultancy Project CCC", team:"XXX", teamLeader:"XXX", startDate:"01/08/2022", targetEndDate: "20/01/2024", client:"Client E", subsidiary:"Subsidiary B"},
  {id: 3,projectCode:"M1001",projectName:"Consultancy Project A", team:"YYY", teamLeader:"YYY", startDate:"01/07/2022", targetEndDate: "01/04/2024", client:"Client B", subsidiary:"N/A"},
  {id: 4,projectCode:"M1301",projectName:"Consultancy Project AAAA", team:"YYY", teamLeader:"YYY", startDate:"01/09/2022", targetEndDate: "20/02/2024", client:"Client C", subsidiary:"Subsidiary A"},
  {id: 5,projectCode:"M1354",projectName:"Consultancy Project BBB", team:"YYY", teamLeader:"YYY", startDate:"01/02/2023", targetEndDate: "31/01/2024", client:"Client D", subsidiary:"Subsidiary C"}
  ]

  const rows1 = [{id: 1,projectCode:"M1201",projectName:"Consultancy Project C", team:"XXX", teamLeader:"XXX", startDate:"01/08/2022", targetEndDate: "01/05/2024", client:"Client A", subsidiary:"N/A"},
  {id: 2,projectCode:"M1321",projectName:"Consultancy Project CCC", team:"XXX", teamLeader:"XXX", startDate:"01/08/2022", targetEndDate: "20/01/2024", client:"Client E", subsidiary:"Subsidiary B"},
  ]

  const rows2 = [{id: 3,projectCode:"M1001",projectName:"Consultancy Project A", team:"YYY", teamLeader:"YYY", startDate:"01/07/2022", targetEndDate: "01/04/2024", client:"Client B", subsidiary:"N/A"},
  {id: 4,projectCode:"M1301",projectName:"Consultancy Project AAAA", team:"YYY", teamLeader:"YYY", startDate:"01/09/2022", targetEndDate: "20/02/2024", client:"Client C", subsidiary:"Subsidiary A"},
  {id: 5,projectCode:"M1354",projectName:"Consultancy Project BBB", team:"YYY", teamLeader:"YYY", startDate:"01/02/2023", targetEndDate: "31/01/2024", client:"Client D", subsidiary:"Subsidiary C"}
  ]

  // const projectFinancialRows = [{id: 1,projectCode:"M1354",projectName:"Consultanct Project BBB",clientName:"Client D",cashFlowStatus:"Positive",cpi:"1.25", totalFees:"500,000.00", totalBudget:"400,000.00", totalCumulativeExpenditure:"280,000.00", totalInvoicedAmount: "350,000.00", totalUnInvoicedAmount:"150,000.00", totalReceivedAmount:"350,000.00"}
  // ]

  // const clientFinancialRows =[{id: 1,clientCode:"Cust-02",clientName:"Client B",totalProjectInvolved:"1",cashFlowStatus:"Positive",cpi:"1.25", totalFees:"500,000.00", totalBudget:"400,000.00", totalCumulativeExpenditure:"280,000.00", totalInvoicedAmount: "350,000.00", totalUnInvoicedAmount:"150,000.00", totalReceivedAmount:"350,000.00"},
  // {id: 2,clientCode:"Cust-03",clientName:"Client C",totalProjectInvolved:"1",cashFlowStatus:"Positive",cpi:"1.25", totalFees:"500,000.00", totalBudget:"400,000.00", totalCumulativeExpenditure:"280,000.00", totalInvoicedAmount: "350,000.00", totalUnInvoicedAmount:"150,000.00", totalReceivedAmount:"350,000.00"},
  // {id: 3,clientCode:"Cust-04",clientName:"Client D",totalProjectInvolved:"4",cashFlowStatus:"Positive",cpi:"1.25", totalFees:"500,000.00", totalBudget:"400,000.00", totalCumulativeExpenditure:"280,000.00", totalInvoicedAmount: "350,000.00", totalUnInvoicedAmount:"150,000.00", totalReceivedAmount:"350,000.00"}
  // ]

  const [isCardClickedIndex, setIsCardClickedIndex] = React.useState(0);

  const [selectedTeamData, setSelectedTeamData]: any[] = React.useState(rows0);

  const handleCardClick = (r: any, index:any) => {
    fetchTableData(r.teamId)
    fetchProjectTableData(r.teamId)
    setIsCardClickedIndex(index)
  };

  const columns = [
    {
      id: 'customerCode',
      field: 'customerCode',
      headerName: t("Client Code"),
      minWidth:50,
      renderCell: (params: any) => (
        <div
          className="text-blue-600 hover:underline cursor-pointer"
          onClick={() => {
            router.push(`/dashboard/ProjectStatusByClient?customerId=${params.row.cid}`);
          }}
        >
          {params.value}
        </div>
      ),
    },
    {
      id: 'customerName',
      field: 'customerName',
      headerName: t("Client Name"),
      minWidth:80
    },
    {
      id: 'projectNo',
      field: 'projectNo',
      headerName: t("Total Project Involved"),
      minWidth:80
    },
    {
      id: 'cashFlowStatus',
      field: 'cashFlowStatus',
      headerName: t("Cash Flow Status"),
      minWidth:100,
      renderCell: (params:any) => {
        console.log(params.row)
        if (params.row.cashFlowStatus === "Positive") {
          return (
            <span className="text-lime-500">{t(params.row.cashFlowStatus)}</span>
          )
        } else if (params.row.cashFlowStatus === "Negative") {
          return (
            <span className="text-red-500">{t(params.row.cashFlowStatus)}</span>
          )
        }
      },
  },
  {
      id: 'cpi',
      field: 'cpi',
      headerName: t("CPI"),
      minWidth:50,
      renderCell: (params:any) => {
        if (params.row.cpi >= 1) {
          return (
            <span className="text-lime-500">{params.row.cpi}</span>
          )
        } else if (params.row.cpi < 1) {
          return (
            <span className="text-red-500">{params.row.cpi}</span>
          )
        }
      },
  },
  {
    id: 'projectedCashFlowStatus',
    field: 'projectedCashFlowStatus',
    headerName: t("Projected Cash Flow Status"),
    minWidth:100,
    renderCell: (params:any) => {
      if (params.row.projectedCashFlowStatus === "Positive") {
        return (
          <span className="text-lime-500">{t(params.row.projectedCashFlowStatus)}</span>
        )
      } else if (params.row.projectedCashFlowStatus === "Negative") {
        return (
          <span className="text-red-500">{t(params.row.projectedCashFlowStatus)}</span>
        )
      }
    },
  },
  {
    id: 'projectedCpi',
    field: 'projectedCpi',
    headerName: t("Projected CPI"),
    minWidth:50,
    renderCell: (params:any) => {
      if (params.row.projectedCpi >= 1) {
        return (
          <span className="text-lime-500">{params.row.projectedCpi}</span>
        )
      } else if (params.row.projectedCpi < 1) {
        return (
          <span className="text-red-500">{params.row.projectedCpi}</span>
        )
      }
    },
  },
  {
    id: 'totalFee',
    field: 'totalFee',
    headerName: t("Total Fees")+t("HKD"),
    minWidth:50,
    type: "number",
    renderCell: (params:any) => {
        return (
          <span>${params.row.totalFee.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</span>
        )
    },
  },
  {
    id: 'totalBudget',
    field: 'totalBudget',
    headerName: t("Total Budget")+t("HKD"),
    minWidth:50,
    type: "number",
    renderCell: (params:any) => {
      return (
        <span>${params.row.totalBudget.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</span>
      )
  },
  },
  {
    id: 'totalExpenditure',
    field: 'totalExpenditure',
    headerName: t("Total Cumulative Expenditure")+t("HKD"),
    minWidth:280,
    type: "number",
    renderCell: (params:any) => {
      return (
        <span>${(params.row.totalExpenditure).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</span>
      )
    },
  },
  {
    id: 'manhoursExpenditure',
    field: 'manhoursExpenditure',
    headerName: t("Manpower Expenses")+t("HKD"),
    minWidth:280,
    type: "number",
    renderCell: (params:any) => {
      return (
        <span>${params.row.manhoursExpenditure.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</span>
      )
    },
  },
  {
    id: 'projectExpense',
    field: 'projectExpense',
    headerName: t("Project Expense")+t("HKD"),
    minWidth:280,
    type: "number",
    renderCell: (params:any) => {
      return (
        <span>${(params.row.projectExpense ?? 0).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</span>
      )
    },
  },
  {
    id: 'totalInvoiced',
    field: 'totalInvoiced',
    headerName: t("Total Invoiced Amount")+t("HKD"),
    minWidth:250,
    type: "number",
    renderCell: (params:any) => {
      return (
        <span>${params.row.totalInvoiced.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</span>
      )
    },
  },
  {
    id: 'totalUnInvoiced',
    field: 'totalUnInvoiced',
    headerName: t("Total Un-Invoiced Amount")+t("HKD"),
    minWidth:250,
    type: "number",
    renderCell: (params:any) => {
      return (
        <span>${params.row.totalUninvoiced.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</span>
      )
    },
  },
  {
    id: 'totalReceived',
    field: 'totalReceived',
    headerName: t("Total Received Amount")+t("HKD"),
    minWidth:250,
    type: "number",
    renderCell: (params:any) => {
      return (
        <span>${params.row.totalReceived.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</span>
      )
    },
  },

  //   {
  //     id: 'projectCode',
  //     field: 'projectCode',
  //     headerName: "Project Code",
  //     flex: 1,
  // },
  // {
  //     id: 'projectName',
  //     field: 'projectName',
  //     headerName: "Project Name",
  //     flex: 1,
  // },
  // {
  //   id: 'team',
  //   field: 'team',
  //   headerName: "Team",
  //   flex: 1,
  // },
  // {
  //   id: 'teamLeader',
  //   field: 'teamLeader',
  //   headerName: "Team Leader",
  //   flex: 1,
  // },
  // {
  //   id: 'startDate',
  //   field: 'startDate',
  //   headerName: "Start Date",
  //   flex: 1,
  // },
  // {
  //   id: 'targetEndDate',
  //   field: 'targetEndDate',
  //   headerName: "Target End Date",
  //   flex: 1,
  // },
  // {
  //   id: 'client',
  //   field: 'client',
  //   headerName: "Client",
  //   flex: 1,
  // },
  // {
  //   id: 'subsidiary',
  //   field: 'subsidiary',
  //   headerName: "Subsidiary",
  //   flex: 1,
  // },
];

const columns2 = [
  {
    id: 'projectCode',
    field: 'projectCode',
    headerName: t("Project Code"),
    minWidth:50,
    renderCell: (params: any) => (
      <div
        className="text-blue-600 hover:underline cursor-pointer"
        onClick={() => {
          router.push(`/dashboard/ProjectCashFlow?projectId=${params.row.id}`);
        }}
      >
        {params.value}
      </div>
    ),
  },
  {
    id: 'projectName',
    field: 'projectName',
    headerName: t("Project Name"),
    minWidth:50,
  },
  {
    id: 'customerName',
    field: 'customerName',
    headerName: t("Client Name"),
    minWidth:50,
  },
  {
    id: 'subsidiaryName',
    field: 'subsidiaryName',
    headerName: t("Subsidiary"),
    minWidth:50,
  },
  {
    id: 'cashFlowStatus',
    field: 'cashFlowStatus',
    headerName: t("Cash Flow Status"),
    minWidth:80,
    renderCell: (params:any) => {
      if (params.row.cashFlowStatus === "Positive") {
        return (
          <span className="text-lime-500">{t(params.row.cashFlowStatus)}</span>
        )
      } else if (params.row.cashFlowStatus === "Negative") {
        return (
          <span className="text-red-500">{t(params.row.cashFlowStatus)}</span>
        )
      }
    },
  },
  {
    id: "cpi",
    field: "cpi",
    headerName: "CPI",
    minWidth:50,
    renderCell: (params: any) => {
      if (params.row.cpi >= 1) {
        return <span className="text-lime-500">{params.row.cpi}</span>;
      } else if (params.row.cpi < 1) {
        return <span className="text-red-500">{params.row.cpi}</span>;
      }
    },
  },
  {
    id: 'projectedCashFlowStatus',
    field: 'projectedCashFlowStatus',
    headerName: t("Projected Cash Flow Status"),
    minWidth:100,
    renderCell: (params:any) => {
      if (params.row.projectedCashFlowStatus === "Positive") {
        return (
          <span className="text-lime-500">{t(params.row.projectedCashFlowStatus)}</span>
        )
      } else if (params.row.projectedCashFlowStatus === "Negative") {
        return (
          <span className="text-red-500">{t(params.row.projectedCashFlowStatus)}</span>
        )
      }
    },
  },
  {
    id: 'projectedCpi',
    field: 'projectedCpi',
    headerName: t("Projected CPI"),
    minWidth:50,
    renderCell: (params:any) => {
      if (params.row.projectedCpi >= 1) {
        return (
          <span className="text-lime-500">{params.row.projectedCpi}</span>
        )
      } else if (params.row.projectedCpi < 1) {
        return (
          <span className="text-red-500">{params.row.projectedCpi}</span>
        )
      }
    },
  },
  {
    id: 'totalFees',
    field: 'totalFees',
    headerName: t("Total Fees")+t("HKD"),
    type: "number",
    minWidth:50,
    renderCell: (params:any) => {
        return (
          <span>${params.row.totalFee.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</span>
        )
    },
  },
  {
    id: 'totalBudget',
    field: 'totalBudget',
    headerName: t("Total Budget")+t("HKD"),
    minWidth:50,
    type: "number",
    renderCell: (params:any) => {
      return (
        <span>${params.row.totalBudget.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</span>
      )
  },
  },
  {
    id: 'totalExpenditure',
    field: 'totalExpenditure',
    headerName: t("Total Cumulative Expenditure")+t("HKD"),
    minWidth:250,
    type: "number",
    renderCell: (params:any) => {
      return (
        <span>${(params.row.totalExpenditure).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</span>
      )
    },
  },
  {
    id: 'manhoursExpenditure',
    field: 'manhoursExpenditure',
    headerName: t("Manpower Expenses")+t("HKD"),
    minWidth:280,
    type: "number",
    renderCell: (params:any) => {
      return (
        <span>${params.row.manhoursExpenditure.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</span>
      )
    },
  },
  {
    id: 'projectExpense',
    field: 'projectExpense',
    headerName: t("Project Expense")+t("HKD"),
    minWidth:280,
    type: "number",
    renderCell: (params:any) => {
      return (
        <span>${(params.row.projectExpense ?? 0).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</span>
      )
    },
  },
  {
    id: 'totalInvoicedAmount',
    field: 'totalInvoicedAmount',
    headerName: t("Total Invoiced Amount")+t("HKD"),
    minWidth:250,
    type: "number",
    renderCell: (params:any) => {
      return (
        <span>${params.row.totalInvoiced.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</span>
      )
    },
  },
  {
    id: 'totalUnInvoicedAmount',
    field: 'totalUnInvoicedAmount',
    headerName: t("Total Un-Invoiced Amount")+t("HKD"),
    minWidth:250,
    type: "number",
    renderCell: (params:any) => {
      return (
        <span>${params.row.totalUninvoiced.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</span>
      )
    },
  },
  {
    id: 'totalReceivedAmount',
    field: 'totalReceivedAmount',
    headerName: t("Total Received Amount") +t("HKD"),
    minWidth:250,
    type: "number",
    renderCell: (params:any) => {
      return (
        <span>${params.row.totalReceived.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</span>
      )
    },
  },
];

  const handleSelectionChange = (newSelectionModel: GridRowSelectionModel) => {
    const selectedRowsData = selectedTeamData.filter((row: any) =>
      newSelectionModel.includes(row.id),
    );
    console.log(selectedRowsData);
  };
  
  const fetchProjectTableData = async (teamId?:any,customerId?:any) => {
    const financialSummaryByProject = await searchFinancialSummaryByProject(teamId);
    setProjectFinancialRows(financialSummaryByProject)
    console.log(financialSummaryByProject)
    setFilteredProjectResult(financialSummaryByProject)
  }

  const handleRowClick = (params:any) => {
    console.log(params.row.teamId);
    // fetchProjectTableData(params.row.teamId,params.row.cid)
  };

  const handleExportByClient = async () => {
    const response = await exportFinancialSummaryByClientExcel({financialSummaryByClients: clientFinancialRows})
    if (response) {
        downloadFile(new Uint8Array(response.blobValue), response.filename!!)
    }
    console.log(clientFinancialRows)
  };

  const handleExportByProject = async () => {
    const response = await exportFinancialSummaryByProjectExcel({financialSummaryByProjects: projectFinancialRows})
    if (response) {
        downloadFile(new Uint8Array(response.blobValue), response.filename!!)
    }
    console.log(projectFinancialRows)
  };

  return (
      <Grid item sm>
        <Typography variant="h4" marginInlineEnd={2}>
          {t("Financial Summary")}
        </Typography>
        <Card className="mt-5">
          <CardHeader className="text-slate-500" title= {t("Active Project Financial Status")}/>
          <div className="ml-10 mr-10" style={{ display: 'flex', flexWrap: 'wrap', justifyContent: 'start'}}>
            {projectFinancialData.map((record:any, index:any) => (
              <div className="hover:cursor-pointer ml-4 mt-5 mb-4 inline-block" key={index} onClick={(r) => handleCardClick(record,index)}>
                    <ProjectFinancialCard 
                    Title={record.teamName == "All Team" ? t("All Team") : record.teamName} 
                    TeamId={record.teamId} TotalActiveProjectNumber={record.projectNo} 
                    TotalFees={record.totalFee} TotalBudget={record.totalBudget} 
                    TotalCumulative={record.manhoursExpenditure ?? 0} 
                    TotalProjectExpense={record.projectExpense ?? 0} 
                    TotalInvoicedAmount={record.totalInvoiced ?? 0} 
                    TotalUnInvoicedAmount={record.unInvoiced ?? 0} 
                    TotalReceivedAmount={record.totalReceived ?? 0} 
                    CashFlowStatus={record.cashFlowStatus ?? "Negative"} 
                    CostPerformanceIndex={record.cpi ?? 0} 
                    ProjectedCashFlowStatus={record.projectedCashFlowStatus ?? "Negative"} 
                    ProjectedCPI={record.projectedCpi ?? 0} 
                    ClickedIndex={isCardClickedIndex} 
                    Index={index}/>
              </div>
            ))}
          </div>
          {/* <hr></hr>
          <div className="ml-10 text-base"><strong>-{t("Formula")}-</strong></div>
          <div className="ml-10 text-sm"><strong>CPI:</strong> {t("Invoiced Amount")} / {t("Cumulative Expenditure")}</div>
          <div className="ml-10 text-sm"><strong>{t("Cash Flow Status")}: </strong>{`${t("Positive when CPI")}`}</div>
          <div className="ml-10 text-sm"><strong>{t("Projected CPI")}:</strong> {t("Project Fee")} / {t("Cumulative Expenditure")}</div>
          <div className="ml-10 text-sm mb-5"><strong>{t("Cash Flow Status")}: </strong>{t("Positive when Projected CPI")}</div> */}
        </Card>
        <Card className="mt-5">
          <div style={{display:"inline-block"}}>
            <CardHeader className="text-slate-500" title={t("Financial Status (by Project)")}/>
          </div>
          <div style={{display:"inline-block"}}>
            {projectFinancialRows.length > 0 && (
              <button onClick={handleExportByProject} className="hover:cursor-pointer hover:bg-lime-50 text-base bg-transparent border-lime-600 text-lime-600 border-solid rounded-md w-36">
                  {t("Export Excel")}
              </button>
            )}
          </div>
          {projectFinancialRows.length > 0 && (
              <SearchBox
                  criteria={projectSearchCriteria}
                  onSearch={(query) => {
                    setFilteredProjectResult(
                      projectFinancialRows.filter(
                        (cp:any) =>
                          cp.projectCode.toLowerCase().includes(query.projectCode.toLowerCase()) &&
                          cp.projectName.toLowerCase().includes(query.projectName.toLowerCase()) 
                      ),
                    );
                  }}
              />
            )}
          <div style={{display:"inline-block",width:"99%",marginLeft:10}}>
            <CustomDatagrid rows={filteredProjectResult} columns={columns2} columnWidth={200} dataGridHeight={300}/>
          </div>
          {/* <hr></hr>
          <div className="ml-10 text-base"><strong>-Formula-</strong></div>
          <div className="ml-10 text-sm"><strong>CPI:</strong> Invoiced Amount / Cumulative Expenditure</div>
          <div className="ml-10 text-sm"><strong>Cash Flow Status: </strong>{`Positive when CPI >= 1`}</div>
          <div className="ml-10 text-sm"><strong>Projected CPI:</strong> Project Fee / Cumulative Expenditure</div>
          <div className="ml-10 text-sm mb-5"><strong>Cash Flow Status: </strong>{`Positive when Projected CPI >= 1`}</div> */}
        </Card>
        <Card className="mt-5">
          <div style={{display:"inline-block"}}>
            <CardHeader className="text-slate-500" title= {t("Financial Status (by Client)")}/>
          </div>
          <div style={{display:"inline-block"}}>
            {clientFinancialRows.length > 0 && (
              <button onClick={handleExportByClient} className="hover:cursor-pointer hover:bg-lime-50 text-base bg-transparent border-lime-600 text-lime-600 border-solid rounded-md w-36">
                  {t("Export Excel")}
              </button>
            )}
          </div>
          {clientFinancialRows.length > 0 && (
              <SearchBox
                  criteria={clientSearchCriteria}
                  onSearch={(query) => {
                    setFilteredClientResult(
                      clientFinancialRows.filter(
                        (cp:any) =>
                          cp.customerCode.toLowerCase().includes(query.customerCode.toLowerCase()) &&
                          cp.customerName.toLowerCase().includes(query.customerName.toLowerCase()) 
                      ),
                    );
                  }}
              />
            )}
          <div style={{display:"inline-block",width:"99%",marginLeft:10}}>
            {/* <CustomDatagrid rows={clientFinancialRows} columns={columns} columnWidth={200} dataGridHeight={300} checkboxSelection={true} onRowSelectionModelChange={handleSelectionChange} selectionModel={selectionModel}/> */}
            <CustomDatagrid onRowClick={handleRowClick} rows={filteredClientResult} columns={columns} columnWidth={200} dataGridHeight={300}/>
          </div>
          {/* <hr></hr>
          <div className="ml-10 text-base"><strong>-Formula-</strong></div>
          <div className="ml-10 text-sm"><strong>CPI:</strong> Invoiced Amount / Cumulative Expenditure</div>
          <div className="ml-10 text-sm"><strong>Cash Flow Status: </strong>{`Positive when CPI >= 1`}</div>
          <div className="ml-10 text-sm"><strong>Projected CPI:</strong> Project Fee / Cumulative Expenditure</div>
          <div className="ml-10 text-sm mb-5"><strong>Cash Flow Status: </strong>{`Positive when Projected CPI >= 1`}</div> */}
        </Card>
      </Grid>
  );
};

export default ProjectFinancialSummary;
