"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, searchFinancialSummaryByClient,searchFinancialSummaryByProject } from "@/app/api/financialsummary/actions";
import ProjectFinancialCard from "./ProjectFinancialCard";
import VisibilityIcon from '@mui/icons-material/Visibility';
import { downloadFile } from "@/app/utils/commonUtil";

const ProjectFinancialSummary: React.FC = () => {
  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 fetchData = async () => {
    const financialSummaryCard = await fetchFinancialSummaryCard();
    setProjectFinancialData(financialSummaryCard)
  }
  const fetchTableData = async (teamId?:any) => {
    const financialSummaryByClient = await searchFinancialSummaryByClient(teamId);
    
    console.log(financialSummaryByClient)
    // console.log(financialSummaryByProject)
    setClientFinancialRows(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)
    setIsCardClickedIndex(index)
  };

  const columns = [
    {
      id: 'customerCode',
      field: 'customerCode',
      headerName: "Client Code",
      minWidth:50
    },
    {
      id: 'customerName',
      field: 'customerName',
      headerName: "Client Name",
      minWidth:80
    },
    {
      id: 'projectNo',
      field: 'projectNo',
      headerName: "Total Project Involved",
      minWidth:80
    },
    {
      id: 'cashFlowStatus',
      field: 'cashFlowStatus',
      headerName: "Cash Flow Status",
      minWidth:100,
      renderCell: (params:any) => {
        console.log(params.row)
        if (params.row.cashFlowStatus === "Positive") {
          return (
            <span className="text-lime-500">{params.row.cashFlowStatus}</span>
          )
        } else if (params.row.cashFlowStatus === "Negative") {
          return (
            <span className="text-red-500">{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: "Projected Cash Flow Status",
    minWidth:100,
    renderCell: (params:any) => {
      if (params.row.projectedCashFlowStatus === "Positive") {
        return (
          <span className="text-lime-500">{params.row.projectedCashFlowStatus}</span>
        )
      } else if (params.row.projectedCashFlowStatus === "Negative") {
        return (
          <span className="text-red-500">{params.row.projectedCashFlowStatus}</span>
        )
      }
    },
  },
  {
    id: 'projectedCpi',
    field: 'projectedCpi',
    headerName: "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: "Total Fees (HKD)",
    minWidth:50,
    renderCell: (params:any) => {
        return (
          <span>${params.row.totalFee.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</span>
        )
    },
  },
  {
    id: 'totalBudget',
    field: 'totalBudget',
    headerName: "Total Budget (HKD)",
    minWidth:50,
    renderCell: (params:any) => {
      return (
        <span>${params.row.totalBudget.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</span>
      )
  },
  },
  {
    id: 'cumulativeExpenditure',
    field: 'cumulativeExpenditure',
    headerName: "Total Cumulative Expenditure (HKD)",
    minWidth:280,
    renderCell: (params:any) => {
      return (
        <span>${params.row.cumulativeExpenditure.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</span>
      )
    },
  },
  {
    id: 'totalInvoiced',
    field: 'totalInvoiced',
    headerName: "Total Invoiced Amount (HKD)",
    minWidth:250,
    renderCell: (params:any) => {
      return (
        <span>${params.row.totalInvoiced.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</span>
      )
    },
  },
  {
    id: 'totalUnInvoiced',
    field: 'totalUnInvoiced',
    headerName: "Total Un-invoiced Amount (HKD)",
    minWidth:250,
    renderCell: (params:any) => {
      return (
        <span>${params.row.totalUninvoiced.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</span>
      )
    },
  },
  {
    id: 'totalReceived',
    field: 'totalReceived',
    headerName: "Total Received Amount (HKD)",
    minWidth:250,
    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: "Project Code",
    minWidth:50,
  },
  {
    id: 'projectName',
    field: 'projectName',
    headerName: "Project Name",
    minWidth:50,
  },
  {
    id: 'customerName',
    field: 'customerName',
    headerName: "Client Name",
    minWidth:50,
  },
  {
    id: 'subsidiaryName',
    field: 'subsidiaryName',
    headerName: "Subsidiary",
    minWidth:50,
  },
  {
    id: 'cashFlowStatus',
    field: 'cashFlowStatus',
    headerName: "Cash Flow Status",
    minWidth:80,
    renderCell: (params:any) => {
      if (params.row.cashFlowStatus === "Positive") {
        return (
          <span className="text-lime-500">{params.row.cashFlowStatus}</span>
        )
      } else if (params.row.cashFlowStatus === "Negative") {
        return (
          <span className="text-red-500">{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: "Projected Cash Flow Status",
    minWidth:100,
    renderCell: (params:any) => {
      if (params.row.projectedCashFlowStatus === "Positive") {
        return (
          <span className="text-lime-500">{params.row.projectedCashFlowStatus}</span>
        )
      } else if (params.row.projectedCashFlowStatus === "Negative") {
        return (
          <span className="text-red-500">{params.row.projectedCashFlowStatus}</span>
        )
      }
    },
  },
  {
    id: 'projectedCpi',
    field: 'projectedCpi',
    headerName: "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: "Total Fees (HKD)",
    minWidth:50,
    renderCell: (params:any) => {
        return (
          <span>${params.row.totalFee.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</span>
        )
    },
  },
  {
    id: 'totalBudget',
    field: 'totalBudget',
    headerName: "Total Budget (HKD)",
    minWidth:50,
    renderCell: (params:any) => {
      return (
        <span>${params.row.totalBudget.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</span>
      )
  },
  },
  {
    id: 'totalCumulativeExpenditure',
    field: 'totalCumulativeExpenditure',
    headerName: "Total Cumulative Expenditure (HKD)",
    minWidth:250,
    renderCell: (params:any) => {
      return (
        <span>${params.row.cumulativeExpenditure.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</span>
      )
    },
  },
  {
    id: 'totalInvoicedAmount',
    field: 'totalInvoicedAmount',
    headerName: "Total Invoiced Amount (HKD)",
    minWidth:250,
    renderCell: (params:any) => {
      return (
        <span>${params.row.totalInvoiced.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</span>
      )
    },
  },
  {
    id: 'totalUnInvoicedAmount',
    field: 'totalUnInvoicedAmount',
    headerName: "Total Un-invoiced Amount (HKD)",
    minWidth:250,
    renderCell: (params:any) => {
      return (
        <span>${params.row.totalUninvoiced.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</span>
      )
    },
  },
  {
    id: 'totalReceivedAmount',
    field: 'totalReceivedAmount',
    headerName: "Total Received Amount (HKD)",
    minWidth:250,
    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,customerId);
    setProjectFinancialRows(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 = () => {
    console.log(projectFinancialRows)
  };

  return (
      <Grid item sm>
        <Card>
          <CardHeader className="text-slate-500" title="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} TotalActiveProjectNumber={record.projectNo} TotalFees={record.totalFee} TotalBudget={record.totalBudget} TotalCumulative={record.cumulativeExpenditure ?? 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>
        </Card>
        <Card className="mt-5">
          <div style={{display:"inline-block"}}>
            <CardHeader className="text-slate-500" title="Financial Status (by Client)"/>
          </div>
          <div style={{display:"inline-block"}}>
            {clientFinancialRows.length > 0 && (
              <button onClick={handleExportByClient} className="hover:cursor-pointer hover:bg-violet-50 text-base bg-transparent border-violet-500 text-violet-500 border-solid rounded-md w-36">
                  Export Excel
              </button>
            )}
          </div>
          <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={clientFinancialRows} columns={columns} columnWidth={200} dataGridHeight={300}/>
          </div>
        </Card>
        <Card className="mt-5">
          <div style={{display:"inline-block"}}>
            <CardHeader className="text-slate-500" title="Financial Status (by Project)"/>
          </div>
          <div style={{display:"inline-block"}}>
            {projectFinancialRows.length > 0 && (
              <button onClick={handleExportByProject} className="hover:cursor-pointer hover:bg-violet-50 text-base bg-transparent border-violet-500 text-violet-500 border-solid rounded-md w-36">
                  Export Excel
              </button>
            )}
          </div>
          <div style={{display:"inline-block",width:"99%",marginLeft:10}}>
            <CustomDatagrid rows={projectFinancialRows} columns={columns2} columnWidth={200} dataGridHeight={300}/>
          </div>
        </Card>
      </Grid>
  );
};

export default ProjectFinancialSummary;
