"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 ProgressCashFlowSearch from "@/components/ProgressCashFlowSearch";
import { Input, Label } from "reactstrap";

const ProjectCashFlow: React.FC = () => {
  const todayDate = new Date();
  const [selectionModel, setSelectionModel]: any[] = React.useState([]);
  const [cashFlowYear, setCashFlowYear]: any[] = React.useState(
    todayDate.getFullYear(),
  );
  const [anticipateCashFlowYear, setAnticipateCashFlowYear]: any[] = React.useState(
    todayDate.getFullYear(),
  );
  const columns = [
    {
      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 ledgerColumns = [
    {
      id: "date",
      field: "date",
      headerName: "Date",
      flex: 0.5,
    },
    {
      id: "expenditure",
      field: "expenditure",
      headerName: "Expenditure (HKD)",
      flex: 0.6,
    },
    {
      id: "income",
      field: "income",
      headerName: "Income (HKD)",
      flex: 0.6,
    },
    {
      id: "cashFlowBalance",
      field: "cashFlowBalance",
      headerName: "Cash Flow Balance (HKD)",
      flex: 0.6,
    },
    {
      id: "remarks",
      field: "remarks",
      headerName: "Remarks",
      flex: 1,
    },
  ];

  const options: ApexOptions = {
    chart: {
      height: 350,
      type: "line",
    },
    stroke: {
      width: [0, 0, 2, 2],
    },
    plotOptions: {
      bar: {
        horizontal: false,
        distributed: false,
      },
    },
    dataLabels: {
      enabled: false,
    },
    xaxis: {
      categories: [
        "Q1",
        "Q2",
        "Q3",
        "Q4",
        "Q5",
        "Q6",
        "Q7",
        "Q8",
        "Q9",
        "Q10",
        "Q11",
        "Q12",
      ],
    },
    yaxis: [
      {
        title: {
          text: "Monthly Income and Expenditure(HKD)",
        },
        min: 0,
        max: 350000,
        tickAmount: 5,
        labels: {
          formatter: function (val) {
              return val.toLocaleString()
          }
        }
      },
      {
        show: false,
        seriesName: "Monthly_Expenditure",
        title: {
          text: "Monthly Expenditure (HKD)",
        },
        min: 0,
        max: 350000,
        tickAmount: 5,
      },
      {
        seriesName: "Cumulative_Income",
        opposite: true,
        title: {
          text: "Cumulative Income and Expenditure(HKD)",
        },
        min: 0,
        max: 850000,
        tickAmount: 5,
        labels: {
          formatter: function (val) {
              return val.toLocaleString()
          }
        }
      },
      {
        show: false,
        seriesName: "Cumulative_Expenditure",
        opposite: true,
        title: {
          text: "Cumulative Expenditure (HKD)",
        },
        min: 0,
        max: 850000,
        tickAmount: 5,
      },
    ],
    grid: {
      borderColor: "#f1f1f1",
    },
    annotations: {},
    series: [
      {
        name: "Monthly_Income",
        type: "column",
        color: "#ffde91",
        data: [0, 110000, 0, 0, 185000, 0, 0, 189000, 0, 0, 300000, 0],
      },
      {
        name: "Monthly_Expenditure",
        type: "column",
        color: "#82b59a",
        data: [
          0, 160000, 120000, 120000, 55000, 55000, 55000, 55000, 55000, 70000,
          55000, 55000,
        ],
      },
      {
        name: "Cumulative_Income",
        type: "line",
        color: "#EE6D7A",
        data: [
          0, 100000, 100000, 100000, 300000, 300000, 300000, 500000, 500000,
          500000, 800000, 800000,
        ],
      },
      {
        name: "Cumulative_Expenditure",
        type: "line",
        color: "#7cd3f2",
        data: [
          0, 198000, 240000, 400000, 410000, 430000, 510000, 580000, 600000,
          710000, 730000, 790000,
        ],
      },
    ],
  };

  const anticipateOptions: ApexOptions = {
    chart: {
      height: 350,
      type: "line",
    },
    stroke: {
      width: [0, 0, 2, 2],
    },
    plotOptions: {
      bar: {
        horizontal: false,
        distributed: false,
      },
    },
    dataLabels: {
      enabled: false,
    },
    xaxis: {
      categories: [
        "Q1",
        "Q2",
        "Q3",
        "Q4",
        "Q5",
        "Q6",
        "Q7",
        "Q8",
        "Q9",
        "Q10",
        "Q11",
        "Q12",
      ],
    },
    yaxis: [
      {
        title: {
          text: "Anticipate Monthly Income and Expenditure(HKD)",
        },
        min: 0,
        max: 350000,
        tickAmount: 5,
        labels: {
          formatter: function (val) {
              return val.toLocaleString()
          }
        }
      },
      {
        show: false,
        seriesName: "Monthly_Expenditure",
        title: {
          text: "Monthly Expenditure (HKD)",
        },
        min: 0,
        max: 350000,
        tickAmount: 5,
      },
      {
        seriesName: "Cumulative_Income",
        opposite: true,
        title: {
          text: "Cumulative Income and Expenditure(HKD)",
        },
        min: 0,
        max: 850000,
        tickAmount: 5,
        labels: {
          formatter: function (val) {
              return val.toLocaleString()
          }
        }
      },
      {
        show: false,
        seriesName: "Cumulative_Expenditure",
        opposite: true,
        title: {
          text: "Cumulative Expenditure (HKD)",
        },
        min: 0,
        max: 850000,
        tickAmount: 5,
      },
    ],
    grid: {
      borderColor: "#f1f1f1",
    },
    annotations: {},
    series: [
      {
        name: "Monthly_Income",
        type: "column",
        color: "#f1c48a",
        data: [0, 110000, 0, 0, 185000, 0, 0, 189000, 0, 0, 300000, 0],
      },
      {
        name: "Monthly_Expenditure",
        type: "column",
        color: "#89d7f3",
        data: [
          60000, 60000, 60000, 60000, 60000, 60000, 60000, 60000, 60000, 60000,
          60000, 60000,
        ],
      }
    ],
  };

  const accountsReceivableOptions: ApexOptions = {
    colors: ["#20E647"],
    series: [80],
    chart: {
      height: 350,
      type: "radialBar",
    },
    plotOptions: {
      radialBar: {
        hollow: {
          size: "70%",
          background: "#ffffff",
        },
        track: {
          dropShadow: {
            enabled: true,
            top: 2,
            left: 0,
            blur: 4,
            opacity: 0.15,
          },
        },
        dataLabels: {
          name: {
            show: false,
          },
          value: {
            color: "#3e98c7",
            fontSize: "3em",
            show: true,
          },
        },
      },
    },
    fill: {
      type: "gradient",
      gradient: {
        shade: "dark",
        type: "vertical",
        gradientToColors: ["#87D4F9"],
        stops: [0, 100],
      },
    },
    stroke: {
      lineCap: "round",
    },
    labels: ["AccountsReceivable"],
  };

  const expenditureOptions: ApexOptions = {
    colors: ["#20E647"],
    series: [95],
    chart: {
      height: 350,
      type: "radialBar",
    },
    plotOptions: {
      radialBar: {
        hollow: {
          size: "70%",
          background: "#ffffff",
        },
        track: {
          dropShadow: {
            enabled: true,
            top: 2,
            left: 0,
            blur: 4,
            opacity: 0.15,
          },
        },
        dataLabels: {
          name: {
            show: false,
          },
          value: {
            color: "#3e98c7",
            fontSize: "3em",
            show: true,
          },
        },
      },
    },
    fill: {
      type: "gradient",
      gradient: {
        shade: "dark",
        type: "vertical",
        gradientToColors: ["#87D4F9"],
        stops: [0, 100],
      },
    },
    stroke: {
      lineCap: "round",
    },
    labels: ["AccountsReceivable"],
  };

  const rows = [
    {
      id: 1,
      projectCode: "M1001",
      projectName: "Consultancy Project A",
      team: "XXX",
      teamLeader: "XXX",
      startDate: "01/07/2022",
      targetEndDate: "01/04/2024",
      client: "Client B",
      subsidiary: "N/A",
    },
    {
      id: 2,
      projectCode: "M1301",
      projectName: "Consultancy Project AAAA",
      team: "XXX",
      teamLeader: "XXX",
      startDate: "01/09/2022",
      targetEndDate: "20/02/2024",
      client: "Client C",
      subsidiary: "Subsidiary A",
    },
    {
      id: 3,
      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 ledgerRows = [
    {
      id: 1,
      date: "Feb 2023",
      expenditure: "-",
      income: "100,000.00",
      cashFlowBalance: "100,000.00",
      remarks: "Payment Milestone 1 (10%)",
    },
    {
      id: 2,
      date: "Feb 2023",
      expenditure: "160,000.00",
      income: "-",
      cashFlowBalance: "(60,000.00)",
      remarks: "Monthly Manpower Expenditure",
    },
    {
      id: 3,
      date: "Mar 2023",
      expenditure: "160,000.00",
      income: "-",
      cashFlowBalance: "(180,000.00)",
      remarks: "Monthly Manpower Expenditure",
    },
    {
      id: 4,
      date: "Apr 2023",
      expenditure: "120,000.00",
      income: "-",
      cashFlowBalance: "(300,000.00)",
      remarks: "Monthly Manpower Expenditure",
    },
    {
      id: 5,
      date: "May 2023",
      expenditure: "-",
      income: "200,000.00",
      cashFlowBalance: "(100,000.00)",
      remarks: "Payment Milestone 2 (20%)",
    },
    {
      id: 6,
      date: "May 2023",
      expenditure: "40,000.00",
      income: "-",
      cashFlowBalance: "(140,000.00)",
      remarks: "Monthly Manpower Expenditure",
    },
  ];

  const [projectData, setProjectData]: any[] = React.useState(rows);
  const [ledgerData, setLedgerData]: any[] = React.useState(ledgerRows);
  const handleSelectionChange = (newSelectionModel: GridRowSelectionModel) => {
    const selectedRowsData = projectData.filter((row: any) =>
      newSelectionModel.includes(row.id),
    );
    console.log(selectedRowsData);
  };

  return (
    <>
      <Suspense fallback={<ProgressCashFlowSearch.Loading />}>
        <ProgressCashFlowSearch />
      </Suspense>
      <CustomDatagrid
        rows={projectData}
        columns={columns}
        columnWidth={200}
        dataGridHeight={300}
        checkboxSelection={true}
        onRowSelectionModelChange={handleSelectionChange}
        selectionModel={selectionModel}
      />
      <Grid item sm>
        <div style={{ display: "inline-block", width: "50%" }}>
          <Grid item xs={12} md={12} lg={12}>
            <Card>
              <CardHeader
                className="text-slate-500"
                title="Project Cash Flow by Month"
              />
              <div style={{ display: "inline-block", width: "99%" }}>
                <div className="inline-block">
                  <Label className="text-slate-500 font-medium ml-6">
                    Period:&nbsp;
                  </Label>
                  <Input
                    id={"cashFlowYear"}
                    value={cashFlowYear}
                    readOnly={true}
                    bsSize="lg"
                    className="rounded-md text-base w-12"
                  />
                </div>
                <div className="inline-block ml-1">
                  <button
                    onClick={() => setCashFlowYear(cashFlowYear - 1)}
                    className="hover:cursor-pointer hover:bg-slate-200 bg-transparent rounded-md w-8 h-8 text-base"
                  >
                    &lt;
                  </button>
                </div>
                <div className="inline-block ml-1">
                  <button
                    onClick={() => setCashFlowYear(cashFlowYear + 1)}
                    className="hover:cursor-pointer hover:bg-slate-200 bg-transparent rounded-md w-8 h-8 text-base"
                  >
                    &gt;
                  </button>
                </div>
                <ReactApexChart
                  options={options}
                  series={options.series}
                  type="line"
                  height="auto"
                />
              </div>
            </Card>
          </Grid>
        </div>
        <div
          style={{
            display: "inline-block",
            width: "24%",
            verticalAlign: "top",
            marginLeft: 10,
          }}
        >
          <Grid item xs={12} md={12} lg={12}>
            <Card>
              <CardHeader
                className="text-slate-500"
                title="Accounts Receivable (HKD)"
              />
              <ReactApexChart
                options={accountsReceivableOptions}
                series={accountsReceivableOptions.series}
                type="radialBar"
              />
              <Card className="ml-2 mr-2 mb-4 rounded-none border-solid border-slate-100">
                <div
                  className="text-sm font-medium ml-5 mt-2"
                  style={{ color: "#898d8d" }}
                >
                  Total Invoiced Amount
                </div>
                <div
                  className="text-lg font-medium ml-5"
                  style={{ color: "#6b87cf" }}
                >
                  1,000,000.00
                </div>
                <hr />
                <div
                  className="text-sm font-medium ml-5"
                  style={{ color: "#898d8d" }}
                >
                  Total Received Amount
                </div>
                <div
                  className="text-lg font-medium ml-5"
                  style={{ color: "#6b87cf" }}
                >
                  800,000.00
                </div>
                <hr />
                <div
                  className="text-sm font-medium ml-5"
                  style={{ color: "#898d8d" }}
                >
                  Accounts Receivable
                </div>
                <div
                  className="text-lg font-medium ml-5 mb-2"
                  style={{ color: "#6b87cf" }}
                >
                  200,000.00
                </div>
              </Card>
            </Card>
          </Grid>
        </div>
        <div
          style={{
            display: "inline-block",
            width: "24%",
            verticalAlign: "top",
            marginLeft: 10,
          }}
        >
          <Grid item xs={12} md={12} lg={12}>
            <Card>
              <CardHeader
                className="text-slate-500"
                title="Expenditure (HKD)"
              />
              <ReactApexChart
                options={expenditureOptions}
                series={expenditureOptions.series}
                type="radialBar"
              />
              <Card className="ml-2 mr-2 mb-4 rounded-none border-solid border-slate-100">
                <div
                  className="text-sm font-medium ml-5 mt-2"
                  style={{ color: "#898d8d" }}
                >
                  Total Budget
                </div>
                <div
                  className="text-lg font-medium ml-5"
                  style={{ color: "#6b87cf" }}
                >
                  800,000.00
                </div>
                <hr />
                <div
                  className="text-sm font-medium ml-5"
                  style={{ color: "#898d8d" }}
                >
                  Total Cumulative Expenditure
                </div>
                <div
                  className="text-lg font-medium ml-5"
                  style={{ color: "#6b87cf" }}
                >
                  760,000.00
                </div>
                <hr />
                <div
                  className="text-sm font-medium ml-5"
                  style={{ color: "#898d8d" }}
                >
                  Accounts Receivable
                </div>
                <div
                  className="text-lg font-medium ml-5 mb-2"
                  style={{ color: "#6b87cf" }}
                >
                  40,000.00
                </div>
              </Card>
            </Card>
          </Grid>
        </div>
        <div
          className="mt-5"
          style={{
            display: "inline-block",
            width: "100%",
            verticalAlign: "top",
          }}
        >
          <Grid item xs={12} md={12} lg={12}>
          <Card>
              <CardHeader
                className="text-slate-500"
                title="Anticipate Cash Flow by Month"
              />
              <div style={{ display: "inline-block", width: "99%" }}>
                <div className="inline-block">
                  <Label className="text-slate-500 font-medium ml-6">
                    Period:&nbsp;
                  </Label>
                  <Input
                    id={"cashFlowYear"}
                    value={anticipateCashFlowYear}
                    readOnly={true}
                    bsSize="lg"
                    className="rounded-md text-base w-12"
                  />
                </div>
                <div className="inline-block ml-1">
                  <button
                    onClick={() => setAnticipateCashFlowYear(cashFlowYear - 1)}
                    className="hover:cursor-pointer hover:bg-slate-200 bg-transparent rounded-md w-8 h-8 text-base"
                  >
                    &lt;
                  </button>
                </div>
                <div className="inline-block ml-1">
                  <button
                    onClick={() => setAnticipateCashFlowYear(cashFlowYear + 1)}
                    className="hover:cursor-pointer hover:bg-slate-200 bg-transparent rounded-md w-8 h-8 text-base"
                  >
                    &gt;
                  </button>
                </div>
                <ReactApexChart
                  options={anticipateOptions}
                  series={anticipateOptions.series}
                  type="line"
                  height="350"
                />
              </div>
            </Card>
            <Card>
              <CardHeader
                className="text-slate-500"
                title="Cash Flow Ledger by Month"
              />
              <div className="ml-4 mr-4">
                <CustomDatagrid
                  rows={ledgerData}
                  columns={ledgerColumns}
                  columnWidth={200}
                  dataGridHeight={300}
                />
              </div>
            </Card>
          </Grid>
        </div>
      </Grid>
    </>
  );
};

export default ProjectCashFlow;
