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 } from "dns";
import SearchBox, { Criterion } from "../SearchBox";
import ProgressByClientSearch from "@/components/ProgressByClientSearch";
import { Suspense } from "react";

const ProgressByClient: React.FC = () => {
  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 [selectionModel, setSelectionModel]: 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] = useState([]);
  const rows = [
    {
      id: 1,
      clientCode: "CUST-001",
      clientName: "Client A",
      clientSubsidiaryCode: "N/A",
      clientSubsidiaryName: "N/A",
      noOfProjects: "5",
    },
    {
      id: 2,
      clientCode: "CUST-001",
      clientName: "Client A",
      clientSubsidiaryCode: "SUBS-001",
      clientSubsidiaryName: "Subsidiary A",
      noOfProjects: "5",
    },
    {
      id: 3,
      clientCode: "CUST-001",
      clientName: "Client A",
      clientSubsidiaryCode: "SUBS-002",
      clientSubsidiaryName: "Subsidiary B",
      noOfProjects: "3",
    },
    {
      id: 4,
      clientCode: "CUST-001",
      clientName: "Client A",
      clientSubsidiaryCode: "SUBS-003",
      clientSubsidiaryName: "Subsidiary C",
      noOfProjects: "1",
    },
  ];
  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,
    },
    {
      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,
    },
    {
      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,
    },
    {
      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,
    },
    {
      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,
    },
  ];

  const columns = [
    {
      id: "clientCode",
      field: "clientCode",
      headerName: "Client Code",
      flex: 1,
    },
    {
      id: "clientName",
      field: "clientName",
      headerName: "Client Name",
      flex: 1,
    },
    {
      id: "clientSubsidiaryCode",
      field: "clientSubsidiaryCode",
      headerName: "Client Subsidiary Code",
      flex: 1,
    },
    {
      id: "noOfProjects",
      field: "noOfProjects",
      headerName: "No. of Projects",
      flex: 1,
    },
  ];

  const columns2 = [
    {
      id: "project",
      field: "project",
      headerName: "Project",
      flex: 1,
    },
    {
      id: "team",
      field: "team",
      headerName: "Team",
      flex: 1,
    },
    {
      id: "teamLeader",
      field: "teamLeader",
      headerName: "Team Leader",
      flex: 1,
    },
    {
      id: "currentStage",
      field: "currentStage",
      headerName: "Current Stage",
      flex: 1,
    },
    {
      id: "budgetedManhour",
      field: "budgetedManhour",
      headerName: "Budgeted Manhour",
      flex: 1,
    },
    {
      id: "spentManhour",
      field: "spentManhour",
      headerName: "Spent Manhour",
      renderCell: (params: any) => {
        if (params.row.budgetedManhour - params.row.spentManhour <= 0) {
          return (
            <span className="text-red-300">{params.row.spentManhour}</span>
          );
        } else {
          return <span>{params.row.spentManhour}</span>;
        }
      },
      flex: 1,
    },
    {
      id: "remainedManhour",
      field: "remainedManhour",
      headerName: "Remained Manhour",
      renderCell: (params: any) => {
        if (params.row.budgetedManhour - params.row.spentManhour <= 0) {
          return (
            <span className="text-red-300">({params.row.remainedManhour})</span>
          );
        } else {
          return <span>{params.row.remainedManhour}</span>;
        }
      },
      flex: 1,
    },
    {
      id: "comingPaymentMilestone",
      field: "comingPaymentMilestone",
      headerName: "Coming Payment Milestone",
      flex: 1,
    },
    {
      id: "alert",
      field: "alert",
      headerName: "Alert",
      renderCell: (params: any) => {
        if (params.row.alert === true) {
          return (
            <span className="text-red-300 text-center">
              <ReportProblemIcon />
            </span>
          );
        } else {
          return <span></span>;
        }
      },
      flex: 1,
    },
  ];

  const InputFields = [
    {
      id: "clientCode",
      label: "Client Code",
      type: "text",
      value: clientCode,
      setValue: setClientCode,
    },
    {
      id: "clientName",
      label: "Client Name",
      type: "text",
      value: clientName,
      setValue: setClientName,
    },
    {
      id: "subsidiaryClientCode",
      label: "Subsidiary Client Code",
      type: "text",
      value: subsidiaryClientCode,
      setValue: setSubsidiaryClientCode,
    },
    {
      id: "subsidiaryClientName",
      label: "Subsidiary Client Name",
      type: "text",
      value: subsidiaryClientName,
      setValue: setSubsidiaryClientName,
    },
    // { id: 'dropdownDemo', label: "dropdownDemo", type: 'dropdown', options: [{id:"1", label:"1"}], value: dropdownDemo, setValue: setDropdownDemo },
    // { id: 'dateDemo', label:'dateDemo', type: 'date', value: dateDemo, setValue: setDateDemo },
    // { id: 'checkboxDemo', label:'checkboxDemo', type: 'checkbox', value: checkboxDemo, setValue: setCheckboxDemo },
    // { id: ['receiptFromDate','receiptToDate'], label: ["收貨日期","收貨日期"], value: [receiptFromDate ? receiptFromDate : null, receiptToDate ? receiptToDate : null],
    //     setValue: [setReceiptFromDate, setReceiptToDate],type: 'dateRange' },
  ];

  const stageDeadline = [
    "31/03/2024",
    "20/02/2024",
    "01/12/2023",
    "05/01/2024",
    "31/03/2023",
  ];

  const series2: ApexAxisChartSeries | ApexNonAxisChartSeries = [
    {
      data: [17.1, 28.6, 5.7, 48.6],
    },
  ];

  const series: ApexAxisChartSeries | ApexNonAxisChartSeries = [
    {
      name: "Project Resource Consumption Percentage",
      data: [80, 55, 40, 65, 70],
    },
  ];

  const options2: ApexOptions = {
    chart: {
      type: "donut",
    },
    plotOptions: {
      pie: {
        donut: {
          labels: {
            show: false,
          },
        },
      },
    },
    labels: [projectArray],
    legend: {
      show: false,
    },
    responsive: [
      {
        breakpoint: 480,
        options: {
          chart: {
            width: 200,
          },
          legend: {
            position: "bottom",
            show: false,
          },
        },
      },
    ],
  };

  const options: ApexOptions = {
    chart: {
      type: "bar",
      height: 350,
    },
    colors: ["#FF4560", "#00E396", "#008FFB", "#775DD0", "#FEB019"],
    plotOptions: {
      bar: {
        horizontal: true,
        distributed: true,
      },
    },
    dataLabels: {
      enabled: false,
    },
    xaxis: {
      categories: [
        "Consultancy Project 123",
        "Consultancy Project 456",
        "Construction Project A",
        "Construction Project B",
        "Construction Project C",
      ],
    },
    yaxis: {
      title: {
        text: "Projects",
      },
      labels: {
        maxWidth: 200,
        style: {
          cssClass: "apexcharts-yaxis-label",
        },
      },
    },
    title: {
      text: "Project Resource Consumption Percentage",
      align: "center",
    },
    grid: {
      borderColor: "#f1f1f1",
    },
    annotations: {},
  };

  const handleSelectionChange = (newSelectionModel: GridRowSelectionModel) => {
    const selectedRowsData = rows2.filter((row) =>
      newSelectionModel.includes(row.id),
    );
    console.log(selectedRowsData);
    const projectArray: any[] = [];
    let otherPercentage = 100;
    let totalBudgetManhour = 0;
    const percentageArray = [];
    for (let i = 0; i <= selectedRowsData.length; i++) {
      if (i === selectedRowsData.length) {
        projectArray.push("Other");
      } else {
        projectArray.push(selectedRowsData[i].project);
        totalBudgetManhour += Number(selectedRowsData[i].budgetedManhour);
      }
    }
    for (let i = 0; i <= selectedRowsData.length; i++) {
      if (i === selectedRowsData.length) {
        percentageArray.push(otherPercentage);
      } else {
        const percentage = (
          (Number(selectedRowsData[i].spentManhour) / totalBudgetManhour) *
          100
        ).toFixed(1);
        percentageArray.push(Number(percentage));
        otherPercentage -= Number(percentage);
      }
    }
    setSelectionModel(newSelectionModel);
    setProjectArray(projectArray);
    setPercentageArray(percentageArray);
  };

  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}/> */}
      <div style={{ display: "inline-block", width: "70%" }}>
        <Grid item xs={12} md={12} lg={12}>
          <Card>
            <CardHeader className="text-slate-500" title="Project Resource Consumption" />
            <div style={{ display: "inline-block", width: "99%" }}>
              <ReactApexChart
                options={options}
                series={series}
                type="bar"
                height={350}
              />
            </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> */}
            <CardHeader
              className="text-slate-500"
              title="Current Stage Due Date"
            />
            <div
              style={{ display: "inline-block", width: "99%", marginLeft: 10 }}
            >
              <CustomDatagrid
                rows={rows2}
                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}>
          <Card style={{ marginLeft: 15, marginRight: 20 }}>
            <CardHeader
              className="text-slate-500"
              title="Overall Progress per Project"
            />
            <ReactApexChart
              options={options2}
              series={percentageArray}
              type="donut"
            />
          </Card>
        </Grid>
      </div>
    </Grid>
  );
};

export default ProgressByClient;
