"use client";

import {
  FinancialByProject,
} from "@/app/api/financialsummary";
import SearchBox, { Criterion } from "../SearchBox";
import { useEffect, useMemo, useState } from "react";
import CustomDatagrid from "../CustomDatagrid";
import { useTranslation } from "react-i18next";
import { useRouter } from "next/navigation";
import { Box, Card, CardHeader } from "@mui/material";
import { SumOfByClient } from "./gptFn";
import { exportFinancialSummaryV2ByClientExcel, exportFinancialSummaryV2ByProjectExcel } from "@/app/api/financialsummary/actions";
import { downloadFile } from "@/app/utils/commonUtil";
// import { summarizeFinancialData } from "./gptFn";

interface Props {
  financialSummByProject: FinancialByProject[];
  financialSummByClient: SumOfByClient[];
  isLoading: Boolean
}
type SearchQuery = Partial<Omit<FinancialByProject, "id">>;
type SearchParamNames = keyof SearchQuery;

type SearchQuery2 = Partial<Omit<SumOfByClient, "id">>;
type SearchParamNames2 = keyof SearchQuery2;

const FinancialStatusByProject: React.FC<Props> = ({
  financialSummByProject,
  financialSummByClient,
  isLoading
}) => {
  const { t } = useTranslation("dashboard");
  const router = useRouter();
  const [filteredByProjectRows, setFilteredByProjectRows] = useState(financialSummByProject);
  const [filteredByClientRows, setFilteredByClientRows] = useState(financialSummByClient);

  const greenColor = "text-lime-500";
  const redColor = "text-red-500";
  const searchCriteria: Criterion<SearchParamNames>[] = useMemo(
    () => [
        { label: t("Project Code"), paramName: "projectCode", type: "text" },
        { label: t("Project Name"), paramName: "projectName", type: "text" },
      ],
    [t],
  );

  const searchCriteria2: Criterion<SearchParamNames2>[] = useMemo(
    () => [
        { label: t("Client Code"), paramName: "customerCode", type: "text" },
        { label: t("Client Name"), paramName: "customerName", type: "text" },
      ],
      [t],
  );

  useEffect(() => {
    setFilteredByProjectRows(financialSummByProject);
    setFilteredByClientRows(financialSummByClient)
  }, [financialSummByProject, financialSummByClient]);

  const columns1 = [
    {
      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) => {
        var cumulativeExpenditure = params.row.projectExpense + params.row.manhourExpense
        if (params.row.invoicedAmount >= cumulativeExpenditure) {
          return <span className={greenColor}>{t("Positive")}</span>;
        } else {
          return <span className={redColor}>{t("Negative")}</span>;
        }
      },
    },
    {
      id: "cpi",
      field: "cpi",
      headerName: "CPI",
      minWidth: 50,
      renderCell: (params: any) => {
        var cumulativeExpenditure = params.row.projectExpense + params.row.manhourExpense
        var cpi = params.row.invoicedAmount/cumulativeExpenditure || 0
        return (
          <span className={cpi >= 1 ? greenColor : redColor}>
            {cpi.toLocaleString(undefined, {
              minimumFractionDigits: 2,
              maximumFractionDigits: 2,
            })}
          </span>
        );
      },
    },
    {
      id: "projectedCashFlowStatus",
      field: "projectedCashFlowStatus",
      headerName: t("Projected Cash Flow Status"),
      minWidth: 100,
      renderCell: (params: any) => {
        var cumulativeExpenditure = params.row.projectExpense + params.row.manhourExpense
        if (params.row.totalFee >= cumulativeExpenditure) {
          return <span className={greenColor}>{t("Positive")}</span>;
        } else {
          return <span className={redColor}>{t("Negative")}</span>;
        }
      },
    },
    {
      id: "projectedCpi",
      field: "projectedCpi",
      headerName: t("Projected CPI"),
      minWidth: 50,
      renderCell: (params: any) => {
        var cumulativeExpenditure = params.row.projectExpense + params.row.manhourExpense
        var projectedCpi = params.row.totalFee/cumulativeExpenditure == Infinity ? 'N/A' : params.row.totalFee/cumulativeExpenditure
        return (
          <span
            className={(typeof projectedCpi == "number" && projectedCpi >= 1 ? greenColor : redColor)}
          >
            {typeof projectedCpi == "number" ? projectedCpi.toLocaleString(undefined, {
              minimumFractionDigits: 2,
              maximumFractionDigits: 2,
            }) : projectedCpi}
          </span>
        );
      },
    },
    {
      id: "totalFee",
      field: "totalFee",
      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: "cumulativeExpenditure",
      field: "cumulativeExpenditure",
      headerName: t("Total Cumulative Expenditure") + t("HKD"),
      minWidth: 250,
      type: "number",
      renderCell: (params: any) => {
        var cumulativeExpenditure = params.row.projectExpense + params.row.manhourExpense
        return (
          <span>
            $
            {cumulativeExpenditure.toLocaleString(undefined, {
              minimumFractionDigits: 2,
              maximumFractionDigits: 2,
            })}
          </span>
        );
      },
    },
    {
      id: "manhourExpense",
      field: "manhourExpense",
      headerName: t("Manpower Expenses") + t("HKD"),
      minWidth: 280,
      type: "number",
      renderCell: (params: any) => {
        return (
          <span>
            $
            {params.row.manhourExpense.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: "invoicedAmount",
      field: "invoicedAmount",
      headerName: t("Total Invoiced Amount") + t("HKD"),
      minWidth: 250,
      type: "number",
      renderCell: (params: any) => {
        return (
          <span>
            $
            {params.row.invoicedAmount.toLocaleString(undefined, {
              minimumFractionDigits: 2,
              maximumFractionDigits: 2,
            })}
          </span>
        );
      },
    },
    {
      id: "nonInvoicedAmount",
      field: "nonInvoicedAmount",
      headerName: t("Total Un-Invoiced Amount") + t("HKD"),
      minWidth: 250,
      type: "number",
      renderCell: (params: any) => {
        var fee = params.row.totalFee
        var invoiced = params.row.invoicedAmount
        var nonInvoiced = fee - invoiced < 0 ? 0 : fee - invoiced
        return (
          <span>
            $
            {Math.abs(nonInvoiced).toLocaleString(undefined, {
              minimumFractionDigits: 2,
              maximumFractionDigits: 2,
            })}
          </span>
        );
      },
    },
    {
      id: "paidAmount",
      field: "paidAmount",
      headerName: t("Total Received Amount") + t("HKD"),
      minWidth: 250,
      type: "number",
      renderCell: (params: any) => {
        return (
          <span>
            $
            {params.row.paidAmount.toLocaleString(undefined, {
              minimumFractionDigits: 2,
              maximumFractionDigits: 2,
            })}
          </span>
        );
      },
    },
  ];

  const columns2 = [
    {
      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.id}`
            );
          }}
        >
          {params.value}
        </div>
      ),
    },
    {
      id: "customerName",
      field: "customerName",
      headerName: t("Client Name"),
      minWidth: 80,
    },
    {
      id: "sumOfProjects",
      field: "sumOfProjects",
      headerName: t("Total Project Involved"),
      minWidth: 80,
    },
    {
      id: "cashFlowStatus",
      field: "cashFlowStatus",
      headerName: t("Cash Flow Status"),
      minWidth: 100,
      renderCell: (params: any) => {
        var cumulativeExpenditure = params.row.projectExpense + params.row.manhourExpense
        return params.row.invoicedAmount >= cumulativeExpenditure ?
        <span className={greenColor}>{t("Positive")}</span>
        : <span className={redColor}>{t("Negative")}</span>
      },
    },
    {
      id: "cpi",
      field: "cpi",
      headerName: t("CPI"),
      minWidth: 50,
      renderCell: (params: any) => {
        var cumulativeExpenditure = params.row.projectExpense + params.row.manhourExpense
        var cpi = cumulativeExpenditure != 0 ? params.row.invoicedAmount/cumulativeExpenditure : 0
        var cpiString = cpi.toLocaleString(undefined, {
            minimumFractionDigits: 2,
            maximumFractionDigits: 2,
          })
        return (cpi >= 1) ?
        <span className={greenColor}>{cpiString}</span>:
        <span className={redColor}>{cpiString}</span>
      },
    },
    {
      id: "projectedCashFlowStatus",
      field: "projectedCashFlowStatus",
      headerName: t("Projected Cash Flow Status"),
      minWidth: 100,
      renderCell: (params: any) => {
        var cumulativeExpenditure = params.row.projectExpense + params.row.manhourExpense
        var status = params.row.totalFee >= cumulativeExpenditure
        return status ? 
        <span className={greenColor}>{t("Positive")}</span>
        : <span className={redColor}>{t("Negative")}</span>
      },
    },
    {
      id: "projectedCpi",
      field: "projectedCpi",
      headerName: t("Projected CPI"),
      minWidth: 50,
      renderCell: (params: any) => {
        var cumulativeExpenditure = params.row.projectExpense + params.row.manhourExpense
        var projectCpi = cumulativeExpenditure != 0 ? params.row.totalFee/cumulativeExpenditure : 0
        var projectCpiString = projectCpi.toLocaleString(undefined, {
            minimumFractionDigits: 2,
            maximumFractionDigits: 2,
          })
        if (projectCpi >= 1) {
          return <span className={greenColor}>{projectCpiString}</span>;
        } else {
          return <span className={redColor}>{projectCpiString}</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: "cumulativeExpenditure",
      field: "cumulativeExpenditure",
      headerName: t("Total Cumulative Expenditure") + t("HKD"),
      minWidth: 280,
      type: "number",
      renderCell: (params: any) => {
        var cumulativeExpenditure = params.row.projectExpense + params.row.manhourExpense
        return (
          <span>
            $
            {cumulativeExpenditure.toLocaleString(undefined, {
              minimumFractionDigits: 2,
              maximumFractionDigits: 2,
            })}
          </span>
        );
      },
    },
    {
      id: "manhourExpense",
      field: "manhourExpense",
      headerName: t("Manpower Expenses") + t("HKD"),
      minWidth: 280,
      type: "number",
      renderCell: (params: any) => {
        return (
          <span>
            $
            {params.row.manhourExpense.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: "invoicedAmount",
      field: "invoicedAmount",
      headerName: t("Total Invoiced Amount") + t("HKD"),
      minWidth: 250,
      type: "number",
      renderCell: (params: any) => {
        return (
          <span>
            $
            {params.row.invoicedAmount.toLocaleString(undefined, {
              minimumFractionDigits: 2,
              maximumFractionDigits: 2,
            })}
          </span>
        );
      },
    },
    {
      id: "nonInvoicedAmount",
      field: "nonInvoicedAmount",
      headerName: t("Total Un-Invoiced Amount") + t("HKD"),
      minWidth: 250,
      type: "number",
      renderCell: (params: any) => {
        var fee = params.row.totalFee
        var invoiced = params.row.invoicedAmount
        var nonInvoiced = fee - invoiced < 0 ? 0 : fee - invoiced
        return (
          <span>
            $
            {nonInvoiced.toLocaleString(undefined, {
              minimumFractionDigits: 2,
              maximumFractionDigits: 2,
            })}
          </span>
        );
      },
    },
    {
      id: "paidAmount",
      field: "paidAmount",
      headerName: t("Total Received Amount") + t("HKD"),
      minWidth: 250,
      type: "number",
      renderCell: (params: any) => {
        return (
          <span>
            $
            {params.row.paidAmount.toLocaleString(undefined, {
              minimumFractionDigits: 2,
              maximumFractionDigits: 2,
            })}
          </span>
        );
      },
    },
  ];

  const handleExportByClient = async () => {
    const response = await exportFinancialSummaryV2ByClientExcel(filteredByClientRows)
    if (response) {
        downloadFile(new Uint8Array(response.blobValue), response.filename!!)
    }
    console.log(filteredByClientRows)
  };

  const handleExportByProject = async () => {
    const response = await exportFinancialSummaryV2ByProjectExcel(filteredByProjectRows)
    if (response) {
        downloadFile(new Uint8Array(response.blobValue), response.filename!!)
    }
    console.log(filteredByProjectRows)
  };

  return (
    <>
      <Box sx={{ mt: 3 }}>
        <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"}}>
            {filteredByProjectRows.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>
          <SearchBox
            criteria={searchCriteria}
            onSearch={(query) => {
              console.log(query)
              if (query.projectCode.length > 0 || query.projectName.length > 0) {
                  setFilteredByProjectRows(
                      financialSummByProject.filter(
                        (cp) =>
                          cp.projectCode.toLowerCase().includes(query.projectCode.trim().toLowerCase()) &&
                          cp.projectName.toLowerCase().includes(query.projectName.trim().toLowerCase()) 
                      ),
                    );
              } else {
                  setFilteredByProjectRows(financialSummByProject)
              }
            }}
          />
          <div style={{ display: "inline-block", width: "99%", marginLeft: 10 }}>
            <CustomDatagrid
              rows={filteredByProjectRows}
              columns={columns1}
              columnWidth={200}
              dataGridHeight={300}
              loading={isLoading}
            />
          </div>
        {/* <SearchResults<StaffResult> items={filteredStaff} columns={columns} /> */}
        </Card>
      </Box>
      <Box sx={{ mt: 3 }}>
        <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"}}>
            {filteredByProjectRows.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>
          <SearchBox
            criteria={searchCriteria2}
            onSearch={(query) => {
              console.log(query)
              if (query.customerCode.length > 0 || query.customerName.length > 0) {
              setFilteredByClientRows(
                  financialSummByClient.filter(
                      (cp) =>
                      cp.customerCode.toLowerCase().includes(query.customerCode.trim().toLowerCase()) &&
                      cp.customerName.toLowerCase().includes(query.customerName.trim().toLowerCase()) 
                  ),
                  );
              } else {
                  setFilteredByClientRows(financialSummByClient)
              }
            }}
          />
          <div style={{ display: "inline-block", width: "99%", marginLeft: 10 }}>
            <CustomDatagrid
              rows={filteredByClientRows}
              columns={columns2}
              columnWidth={200}
              dataGridHeight={300}
              loading={isLoading}
            />
          </div>
        </Card>
      </Box>
    </>
  );
};
export default FinancialStatusByProject;
