"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 { 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 { ClientSubsidiaryProjectResult } from "@/app/api/clientprojects/actions";
import { ClientProjectResult} from "@/app/api/clientprojects";
import { ConstructionOutlined } from "@mui/icons-material";
import ReactApexChart from "react-apexcharts";
import { ApexOptions } from "apexcharts";
import { useSearchParams } from 'next/navigation';
import { fetchAllClientSubsidiaryProjects,fetchAllClientProjects} from "@/app/api/clientprojects/actions";
// const ReactApexChart = dynamic(() => import('react-apexcharts'), { ssr: false });

type SearchProjectQuery = Partial<Omit<ClientSubsidiaryProjectResult, "id">>;
type SearchProjectParamNames = keyof SearchProjectQuery;

interface Props {
  // clientSubsidiaryProjectResult: ClientSubsidiaryProjectResult[];
}

const ProgressByClient: React.FC<Props> = () => {
  const searchParams = useSearchParams();
  const customerId = searchParams.get('customerId');
  const subsidiaryId = searchParams.get('subsidiaryId');
  const [activeTab, setActiveTab] = useState("financialSummary");
  const [SearchCriteria, setSearchCriteria] = React.useState({});
  const { t } = useTranslation("dashboard");

  const [clientCode, setClientCode] = useState("");
  const [clientName, setClientName] = useState("");
  const [subsidiaryClientCode, setSubsidiaryClientCode] = useState("");
  const [subsidiaryClientName, setSubsidiaryClientName] = useState("");
  const [projectArray, setProjectArray]: any[] = useState([]);
  const [percentageArray, setPercentageArray]: any[] = useState([]);
  const [colorArray, setColorArray]: any[] = useState([]);
  const [selectionModel, setSelectionModel]: any[] = React.useState([]);
  const [pieChartColor, setPieChartColor]: any[] = React.useState([]);
  const [totalSpentPercentage, setTotalSpentPercentage]: any = React.useState();
  const [projectBudgetManhour, setProjectBudgetManhour]: any =
    React.useState("-");
  const [actualManhourSpent, setActualManhourSpent]: any = React.useState("-");
  const [remainedManhour, setRemainedManhour]: any = React.useState("-");
  const [filteredClientSubsidiaryProjectResult, setFilteredClientSubsidiaryProjectResult]:any[] = useState([]);
  const [lastUpdate, setLastUpdate]: any = React.useState("-");
  const [dropdownDemo, setDropdownDemo] = useState("");
  const [dateDemo, setDateDemo] = useState(null);
  const [checkboxDemo, setCheckboxDemo] = useState(false);
  const [receiptFromDate, setReceiptFromDate] = useState(null);
  const [receiptToDate, setReceiptToDate] = useState(null);
  const [selectedRows, setSelectedRows]:any[] = useState([]);
  const [chartProjectName, setChartProjectName]:any[] = useState([]);
  const [chartProjectDisplayName, setChartProjectDisplayName]:any[] = useState([]);
  const [chartProjectBudgetedHour, setChartProjectBudgetedHour]:any[] = useState([]);
  const [chartProjectSpentHour, setChartProjectSpentHour]:any[] = useState([]);
  const [chartManhourConsumptionPercentage, setChartManhourConsumptionPercentage]:any[] = useState([]);
  const color = ["#f57f90", "#94f7d6", "#87c5f5", "#ab95f5", "#fcd68b",
  "#f58a9b", "#8ef4d1", "#92caf9", "#a798f9", "#fad287",
  "#f595a6", "#88f1cc", "#9dcff5", "#a39bf5", "#f8de83",
  "#f5a0b1", "#82eec7", "#a8d4f1", "#9f9ef1", "#f6ea7f",
  "#f5abb4", "#7cebca", "#b3d9ed", "#9ba1ed", "#f4f67b",
  "#f5b6b7", "#76e8cd", "#bed6e9", "#97a4e9", "#f2fa77",
  "#f5c1ba", "#70e5d0", "#c9d3e5", "#93a7e5", "#f0fe73",
  "#f5ccbd", "#6ae2d3", "#d4d0e1", "#8faae1", "#eefe6f",
  "#f5d7c0", "#64dfd6", "#dfc5dd", "#8badd5", "#ecfe6b",
  "#f5e2c3", "#5edcd9", "#eabada", "#87b0c9", "#eafc67",
  "#f5edc6", "#58d9dc", "#f5afd6", "#83b3bd", "#e8fc63",
  "#f5f8c9", "#52d6df", "#ffacd2", "#7fb6b1", "#e6fc5f",
  "#f5ffcc", "#4cd3e2", "#ffa9ce", "#7bb9a5", "#e4fc5b",
  "#f2ffcf", "#46d0e5", "#ffa6ca", "#77bc99", "#e2fc57",
  "#efffd2", "#40cde8", "#ffa3c6", "#73bf8d", "#e0fc53",
  "#ecffd5", "#3acaeb", "#ffa0c2", "#6fc281", "#defb4f",
  "#e9ffd8", "#34c7ee", "#ff9dbe", "#6bc575", "#dcfb4b",
  "#e6ffdb", "#2ec4f1", "#ff9aba", "#67c869", "#dafb47",
  "#e3ffde", "#28c1f4", "#ff97b6", "#63cb5d", "#d8fb43",
  "#e0ffe1", "#22bef7", "#ff94b2", "#5fce51", "#d6fb3f",
  "#ddfee4", "#1cbbfa", "#ff91ae", "#5bd145", "#d4fb3b",
  "#dafee7", "#16b8fd", "#ff8eaa", "#57d439", "#d2fb37",
  "#d7feea", "#10b5ff", "#ff8ba6", "#53d72d", "#d0fb33",
  "#d4feed", "#0ab2ff", "#ff88a2", "#4fda21", "#cefb2f",
  "#d1fef0", "#04afff", "#ff859e", "#4bdd15", "#ccfb2b"];
  const [clientSubsidiaryProjectResult, setClientSubsidiaryProjectResult]:any[] = useState([]);
  const [tableSorting, setTableSorting] = useState('ProjectName');
  const [customerNameAndCode,setCustomerNameAndCode] = useState("");

  const fetchData = async () => {
    const clientprojects = await fetchAllClientProjects();
    for (let i = 0; i < clientprojects.length; i++) {
      if (customerId != null && clientprojects[i].customerId == parseInt(customerId)){
        setCustomerNameAndCode(t("Selected Client") + ": " + clientprojects[i].customerName + " (" + clientprojects[i].customerCode + ")")
      }
    }
    if (customerId && subsidiaryId) {
      try {
        if (subsidiaryId === '-'){
          console.log("ss")
          const clickResult = await fetchAllClientSubsidiaryProjects(
            Number(customerId),tableSorting,Number(0))
            console.log(clickResult)
          setClientSubsidiaryProjectResult(clickResult);
          setFilteredClientSubsidiaryProjectResult(clickResult);
        } else {
          const clickResult = await fetchAllClientSubsidiaryProjects(
            Number(customerId),
            tableSorting,
            Number(subsidiaryId))
            console.log(clickResult)
          setClientSubsidiaryProjectResult(clickResult);
          setFilteredClientSubsidiaryProjectResult(clickResult);
        }
        
        
      } catch (error) {
        console.error('Error fetching client subsidiary projects:', error);
      }
    } else if (customerId) {
      try {
        const clickResult = await fetchAllClientSubsidiaryProjects(
          Number(customerId),tableSorting)
        setClientSubsidiaryProjectResult(clickResult);
        setFilteredClientSubsidiaryProjectResult(clickResult);
      } catch (error) {
        console.error('Error fetching client subsidiary projects:', error);
      }
    }
  }
  
  useEffect(() => {
    const projectCode = []
    const projectName = []
    const projectBudgetedManHour = []
    const projectSpentManHour = []
    const manhourConsumptionPercentage = []
   for (let i = 0; i < clientSubsidiaryProjectResult.length; i++){
    clientSubsidiaryProjectResult[i].color = color[i]
    projectCode.push(clientSubsidiaryProjectResult[i].projectCode + "(" + clientSubsidiaryProjectResult[i].team + ")")
    projectName.push(clientSubsidiaryProjectResult[i].projectName)
    projectBudgetedManHour.push(clientSubsidiaryProjectResult[i].budgetedManhour)
    projectSpentManHour.push(clientSubsidiaryProjectResult[i].spentManhour)
    manhourConsumptionPercentage.push(clientSubsidiaryProjectResult[i].manhourConsumptionPercentage)
   }
   setChartProjectName(projectCode)
   setChartProjectDisplayName(projectName)
   setChartProjectBudgetedHour(projectBudgetedManHour)
   setChartProjectSpentHour(projectSpentManHour)
   setChartManhourConsumptionPercentage(manhourConsumptionPercentage)
  }, [clientSubsidiaryProjectResult]);

  useEffect(() => {
   fetchData()
  }, [customerId,subsidiaryId,tableSorting]);

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

  const rows2 = [
    {
      id: 1,
      project: "Consultancy Project 123",
      team: "XXX",
      teamLeader: "XXX",
      currentStage: "Contract Documentation",
      budgetedManhour: "200.00",
      spentManhour: "120.00",
      remainedManhour: "80.00",
      comingPaymentMilestone: "31/03/2024",
      alert: false,
      color: "#f57f90",
    },
    {
      id: 2,
      project: "Consultancy Project 456",
      team: "XXX",
      teamLeader: "XXX",
      currentStage: "Report Preparation",
      budgetedManhour: "400.00",
      spentManhour: "200.00",
      remainedManhour: "200.00",
      comingPaymentMilestone: "20/02/2024",
      alert: false,
      color: "#94f7d6",
    },
    {
      id: 3,
      project: "Construction Project A",
      team: "YYY",
      teamLeader: "YYY",
      currentStage: "Construction",
      budgetedManhour: "187.50",
      spentManhour: "200.00",
      remainedManhour: "12.50",
      comingPaymentMilestone: "13/12/2023",
      alert: true,
      color: "#87c5f5",
    },
    {
      id: 4,
      project: "Construction Project B",
      team: "XXX",
      teamLeader: "XXX",
      currentStage: "Post Construction",
      budgetedManhour: "100.00",
      spentManhour: "40.00",
      remainedManhour: "60.00",
      comingPaymentMilestone: "05/01/2024",
      alert: false,
      color: "#ab95f5",
    },
    {
      id: 5,
      project: "Construction Project C",
      team: "YYY",
      teamLeader: "YYY",
      currentStage: "Construction",
      budgetedManhour: "300.00",
      spentManhour: "150.00",
      remainedManhour: "150.00",
      comingPaymentMilestone: "31/03/2024",
      alert: false,
      color: "#fcd68b",
    },
  ];

  const columns2 = [
    {
      id: "color",
      field: "color",
      headerName: "",
      renderCell: (param: any) => {
        return (
          <span
            className="dot"
            style={{
              height: "15px",
              width: "15px",
              borderRadius: "50%",
              backgroundColor: `${param.row.color}`,
              display: "inline-block",
            }}
          ></span>
        );
      },
      flex:0.1
    },
    {
      id: "projectCode",
      field: "projectCode",
      headerName: t("Project Code"),
      minWidth:100
    },
    {
      id: "projectName",
      field: "projectName",
      headerName: t("Project Name"),
      minWidth:300
    },
    {
      id: "team",
      field: "team",
      headerName: t("Team"),
      minWidth: 50
    },
    {
      id: "teamLead",
      field: "teamLead",
      headerName: t("Team Leader"),
      minWidth: 70
    },
    {
      id: "expectedStage",
      field: "expectedStage",
      headerName: t("Expected Stage"),
      minWidth: 300,
      renderCell: (params: any) => {
        if (params.row.expectedStage != null){
          const expectedStage = params.row.expectedStage;
          const lines = expectedStage.split(",").map((line:any, index:any) => (
            <React.Fragment key={index}>
              {line.trim()}
              <br />
            </React.Fragment>
          ));
          return <div>{lines}</div>;
        } else {
          return <div>-</div>;
        }
        
      },
    },
    {
      id: "budgetedManhour",
      field: "budgetedManhour",
      headerName: t("Budgeted Manhours"),
      type: "number",
      minWidth: 70,
      renderCell: (params: any) => {
        return <span>{params.row.budgetedManhour.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</span>;
      }
    },
    {
      id: "spentManhour",
      field: "spentManhour",
      headerName: t("Spent Manhours"),
      type: "number",
      renderCell: (params: any) => {
        if (params.row.budgetedManhour - params.row.spentManhour <= 0) {
          return (
            <span className="text-red-300">{params.row.spentManhour.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</span>
          );
        } else {
          console.log(params)
          return <span>{params.row.spentManhour.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</span>;
        }
      },
      minWidth: 70
    },
    {
      id: "remainedManhour",
      field: "remainedManhour",
      headerName: t("Remained Manhours"),
      type: "number",
      renderCell: (params: any) => {
        if (params.row.budgetedManhour - params.row.spentManhour <= 0) {
          return (
            <span className="text-red-300">({params.row.remainedManhour.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })})</span>
          );
        } else {
          return <span>{params.row.remainedManhour.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</span>;
        }
      },
      minWidth: 70
    },
    {
      id: "comingPaymentMilestone",
      field: "comingPaymentMilestone",
      headerName: t("Coming Payment Milestones"),
      minWidth: 100
    },
    {
      id: "alert",
      field: "alert",
      headerName: t("Alert"),
      renderCell: (params: any) => {
        if (params.row.alert === true) {
          return (
            <span className="text-red-300 text-center">
              <ReportProblemIcon />
            </span>
          );
        } else {
          return <span></span>;
        }
      },
      flex:0.1
    },
  ];

  const options2: ApexOptions = {
    chart: {
      type: "donut",
    },
    colors: colorArray,
    plotOptions: {
      pie: {
        donut: {
          labels: {
            show: true,
            name: {
              show: true,
            },
            value: {
              show: true,
              fontWeight: 500,
              fontSize: "30px",
              color: "#3e98c7",
            },
            total: {
              show: true,
              showAlways: true,
              label: t("Spent"),
              fontFamily: "sans-serif",
              formatter: function (val) {
                return totalSpentPercentage + "%";
              },
            },
          },
        },
      },
    },
    labels: projectArray,
    legend: {
      show: false,
    },
    tooltip: {
      enabled: true,
      y: {
        formatter: function (val) {
          return (val.toString().includes(".") ? val.toString() : val.toFixed(1)) + "%";
        }
      }
    },
    responsive: [
      {
        breakpoint: 480,
        options: {
          chart: {
            width: 200,
          },
          legend: {
            position: "bottom",
            show: false,
          },
        },
      },
    ],
  };

  const options: ApexOptions = {
    chart: {
      type: "bar",
      height: 450,
    },
    tooltip: {
      enabled: true, // Enable tooltip
      custom: ({ series, seriesIndex, dataPointIndex, w }) => {

        const projectCode = chartProjectName[dataPointIndex];
        const projectName = chartProjectDisplayName[dataPointIndex];
        const budgetManhours = chartProjectBudgetedHour[dataPointIndex];
        const spentManhours = chartProjectSpentHour[dataPointIndex];
        const value = series[seriesIndex][dataPointIndex];
        const tooltipContent = `
          <div style="width: auto;">
            <span style="font-weight: bold;">${projectCode} - ${projectName}</span>
            <br>
            ${t("Budget Manhours")}: ${budgetManhours.toFixed(2)} hours
            <br>
            ${t("Spent Manhours")}: ${spentManhours.toFixed(2)} hours
            <br>
            Percentage: ${value.toString().includes(".") ? value.toString() : value.toFixed(1)}%
          </div>
        `;

        return tooltipContent;
      },
    },
    series: [{
      name: t("Project Resource Consumption Percentage (%)"),
      data: chartManhourConsumptionPercentage,
    },],
    colors: ["#f57f90", "#94f7d6", "#87c5f5", "#ab95f5", "#fcd68b",
    "#f58a9b", "#8ef4d1", "#92caf9", "#a798f9", "#fad287",
    "#f595a6", "#88f1cc", "#9dcff5", "#a39bf5", "#f8de83",
    "#f5a0b1", "#82eec7", "#a8d4f1", "#9f9ef1", "#f6ea7f",
    "#f5abb4", "#7cebca", "#b3d9ed", "#9ba1ed", "#f4f67b",
    "#f5b6b7", "#76e8cd", "#bed6e9", "#97a4e9", "#f2fa77",
    "#f5c1ba", "#70e5d0", "#c9d3e5", "#93a7e5", "#f0fe73",
    "#f5ccbd", "#6ae2d3", "#d4d0e1", "#8faae1", "#eefe6f",
    "#f5d7c0", "#64dfd6", "#dfc5dd", "#8badd5", "#ecfe6b",
    "#f5e2c3", "#5edcd9", "#eabada", "#87b0c9", "#eafc67",
    "#f5edc6", "#58d9dc", "#f5afd6", "#83b3bd", "#e8fc63",
    "#f5f8c9", "#52d6df", "#ffacd2", "#7fb6b1", "#e6fc5f",
    "#f5ffcc", "#4cd3e2", "#ffa9ce", "#7bb9a5", "#e4fc5b",
    "#f2ffcf", "#46d0e5", "#ffa6ca", "#77bc99", "#e2fc57",
    "#efffd2", "#40cde8", "#ffa3c6", "#73bf8d", "#e0fc53",
    "#ecffd5", "#3acaeb", "#ffa0c2", "#6fc281", "#defb4f",
    "#e9ffd8", "#34c7ee", "#ff9dbe", "#6bc575", "#dcfb4b",
    "#e6ffdb", "#2ec4f1", "#ff9aba", "#67c869", "#dafb47",
    "#e3ffde", "#28c1f4", "#ff97b6", "#63cb5d", "#d8fb43",
    "#e0ffe1", "#22bef7", "#ff94b2", "#5fce51", "#d6fb3f",
    "#ddfee4", "#1cbbfa", "#ff91ae", "#5bd145", "#d4fb3b",
    "#dafee7", "#16b8fd", "#ff8eaa", "#57d439", "#d2fb37",
    "#d7feea", "#10b5ff", "#ff8ba6", "#53d72d", "#d0fb33",
    "#d4feed", "#0ab2ff", "#ff88a2", "#4fda21", "#cefb2f",
    "#d1fef0", "#04afff", "#ff859e", "#4bdd15", "#ccfb2b"],
    plotOptions: {
      bar: {
        horizontal: true,
        distributed: true,
        dataLabels: {
          position: 'top'
        },
      },
    },
    dataLabels: {
      enabled: true,
      textAnchor: 'end',
      formatter: (val) => `${val}%`, 
    },
    xaxis: {
      categories: chartProjectName,
    },
    yaxis: {
      title: {
        text: t("Projects"),
        style: {
          fontSize: "14px",
          fontWeight: "bold",
        },
      },
      labels: {
        maxWidth: 200,
        style: {
          cssClass: "apexcharts-yaxis-label",
        },
      },
    },
    title: {
      text: t("Project Resource Consumption Percentage"),
      align: "center",
    },
    grid: {
      borderColor: "#f1f1f1",
      xaxis: {
        lines: {
          show: true,
        }
      }
    },
    annotations: {},
  };

  const handleSelectionChange = (newSelectionModel: GridRowSelectionModel) => {
    const selectedRowsData:any = clientSubsidiaryProjectResult.filter((row:any) =>
      newSelectionModel.includes(row.id),
    );
    console.log(selectedRowsData);
    const projectArray = [];
    const pieChartColorArray = [];
    let totalSpent = 0;
    let totalBudgetManhour = 0;
    const percentageArray = [];
    for (let i = 0; i <= selectedRowsData.length; i++) {
      if (i === selectedRowsData.length && i > 0) {
        projectArray.push(t("Remained"));
      } else if (selectedRowsData.length > 0) {
        projectArray.push(selectedRowsData[i].projectName);
        totalBudgetManhour += Number(selectedRowsData[i].budgetedManhour);
        totalSpent += Number(selectedRowsData[i].spentManhour);
        pieChartColorArray.push(color[i]);
      }
    }
    for (let i = 0; i <= selectedRowsData.length; i++) {
      if (i === selectedRowsData.length && i > 0) {
        const remainedManhour = totalBudgetManhour - totalSpent;
        percentageArray.push(
          Number(((remainedManhour / totalBudgetManhour) * 100).toFixed(1)),
        );
      } else if (selectedRowsData.length > 0) {
        const percentage = (
          (Number(selectedRowsData[i].spentManhour) / totalBudgetManhour) *
          100
        ).toFixed(1);
        percentageArray.push(Number(percentage));
      }
    }
    setProjectBudgetManhour(totalBudgetManhour.toFixed(2));
    setActualManhourSpent(totalSpent.toFixed(2));
    setRemainedManhour((totalBudgetManhour - totalSpent).toFixed(2));
    setLastUpdate(new Date().toLocaleDateString("en-GB"));
    setSelectionModel(newSelectionModel);
    console.log(projectArray);
    setProjectArray(projectArray);
    setPercentageArray(percentageArray);
    console.log(percentageArray);
    setTotalSpentPercentage(
      ((totalSpent / totalBudgetManhour) * 100).toFixed(1),
    );
    if (projectArray.length > 0 && projectArray.includes(t("Remained"))) {
      const nonLastRecordColors = pieChartColorArray;
      setColorArray([
        ...nonLastRecordColors.slice(0, projectArray.length - 1),
        "#a3a3a3",
      ]);
    } else {
      setColorArray(pieChartColorArray);
    }
  };

  const applySearch = (data: any) => {
    console.log(data);
    setSearchCriteria(data);
  };
  return (
    <Grid item sm>
      {/* <CustomSearchForm applySearch={applySearch} fields={InputFields}/> */}
      {/* <CustomDatagrid rows={rows} columns={columns} columnWidth={200} dataGridHeight={300}/> */}
      {customerNameAndCode !== "" && (
        <div style={{ display: "inline-block", width: "99%" }}>
          <Grid item xs={12} md={12} lg={12}>
              <Card>
              <CardHeader className="text-slate-700" title= {customerNameAndCode} />
              </Card>
          </Grid>
        </div>
      )}
      <div style={{ display: "inline-block", width: "70%" }}>
        <Grid item xs={12} md={12} lg={12}>
          <Card>
            <CardHeader className="text-slate-500" title= {t("Project Resource Consumption")} />
            <div style={{ display: "inline-block", width: "99%" }}>
            <div className="ml-6 text-sm">
                <b>
                  {t("Sorting")}:
                </b>
              </div>
              <div className="ml-6 mb-2">
              <button onClick={() => {setTableSorting('PercentageASC')}}
                className="hover:cursor-pointer hover:bg-lime-50 text-sm bg-transparent border-lime-600 text-lime-600 border-solid w-50"
              >
                {t(`Percentage (Ascending Order)`)}
              </button>
              <button
                  onClick={() => {setTableSorting('PercentageDESC')}}
                  className="hover:cursor-pointer hover:bg-lime-50 text-sm bg-transparent border-lime-600 text-lime-600 border-solid w-50"
                >
                {t(`Percentage (Descending Order)`)}
              </button>
              <button
                  onClick={() => {setTableSorting('ProjectName')}}
                  className="hover:cursor-pointer hover:bg-lime-50 text-sm bg-transparent border-lime-600 text-lime-600 border-solid w-50"
                >
                {t("Project Name")}
              </button>
              </div>
              <ReactApexChart
                options={options}
                series={options.series}
                type="bar"
                height={500}
              />
            </div>
            {/* <div style={{display:"inline-block",width:"20%",verticalAlign:"top",textAlign:"center"}}>
                    <p><strong><u>Stage Deadline</u></strong></p>
                    {stageDeadline.map((date, index) => {
                      const marginTop = index === 0 ? 25 : 20;
                      return (
                        <p style={{marginTop:marginTop}} key={index}>{date}</p>
                      );
                    })}
                  </div> */}
            </Card>
            <Card className="mt-2">
            <CardHeader
              className="text-slate-500"
              title= {t("Resource Consumption and Coming Milestones")}
            />
            {clientSubsidiaryProjectResult.length > 0 && (
              <SearchBox
                  criteria={projectSearchCriteria}
                  onSearch={(query) => {
                    setFilteredClientSubsidiaryProjectResult(
                      clientSubsidiaryProjectResult.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={filteredClientSubsidiaryProjectResult}
                columns={columns2}
                columnWidth={200}
                dataGridHeight={300}
                checkboxSelection={true}
                onRowSelectionModelChange={handleSelectionChange}
                selectionModel={selectionModel}
              />
            </div>
          </Card>
        </Grid>
      </div>
      <div
        style={{
          display: "inline-block",
          width: "30%",
          verticalAlign: "top",
          marginLeft: 0,
        }}
      >
        <Grid item xs={12} md={12} lg={12} style={{height:620}}>
          <Card style={{ marginLeft: 15, marginRight: 20, height:"100%"}}>
            <CardHeader
              className="text-slate-500"
              title= {t("Overall Progress per Project")}
            />
            {percentageArray.length === 0 && (
              <div
                className="mt-40 mb-10 ml-5 mr-5 text-lg font-medium text-center"
                style={{ color: "#898d8d" }}
              >
                {t("Please select the project you want to check.")}
              </div>
            )}
            {percentageArray.length > 0 && (
              <ReactApexChart
                options={options2}
                series={percentageArray}
                type="donut"
                style={{marginTop:'10rem'}}
              />
            )}
          </Card>
        </Grid>
        <Grid item xs={12} md={12} lg={12}>
          <Card style={{ marginLeft: 15, marginRight: 20, marginTop: 20}}>
            <div>
              <div
                className="mt-5 text-lg font-medium"
                style={{ color: "#898d8d" }}
              >
                <span style={{ marginLeft: "5%" }}>{t("Project Budget Manhours")}</span>
              </div>
              <div
                className="mt-2 text-2xl font-extrabold"
                style={{ color: "#6b87cf", textAlign: "right" }}
              >
                <span style={{ margin: "5%" }}>{projectBudgetManhour}</span>
              </div>
            </div>
            <hr />
            <div>
              <div
                className="mt-2 text-lg font-medium"
                style={{ color: "#898d8d" }}
              >
                <span style={{ margin: "5%" }}>{t("Actual Manhours Spent")}</span>
              </div>
              <div
                className="mt-2 text-2xl font-extrabold"
                style={{ color: "#6b87cf", textAlign: "right" }}
              >
                <span style={{ margin: "5%" }}>{actualManhourSpent}</span>
              </div>
            </div>
            <hr />
            <div>
              <div
                className="mt-2 text-lg font-medium"
                style={{ color: "#898d8d" }}
              >
                <span style={{ margin: "5%" }}>{t("Remained Manhours")}</span>
              </div>
              <div
                className="mt-2 text-2xl font-extrabold"
                style={{ color: "#6b87cf", textAlign: "right" }}
              >
                <span style={{ margin: "5%" }}>{remainedManhour}</span>
              </div>
            </div>
            <hr />
            <div>
              <div
                className="mt-2 text-lg font-medium"
                style={{ color: "#898d8d" }}
              >
                <span style={{ margin: "5%" }}>{t("Last Update")}</span>
              </div>
              <div
                className="mt-2 mb-5 text-2xl font-extrabold"
                style={{ color: "#6b87cf", textAlign: "right" }}
              >
                <span style={{ margin: "5%" }}>{lastUpdate}</span>
              </div>
            </div>
          </Card>
        </Grid>
      </div>
    </Grid>
  );
};

export default ProgressByClient;
