import { Card } from "antd";
import dayjs from "../../../utils/day";
import { useTranslation } from "react-i18next";
import _ from "lodash";
import { Area, Bar, CartesianGrid, ComposedChart, Legend, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts";
import Dinero from "dinero.js";
import * as Utils from "../../scoreboard-targets-table/scoreboard-targets-table.util";
import DashboardRefreshRequired from "../refresh-required.component";

export default function DashboardMonthlyRevenueGraph({ data, ...cardProps }) {
  const { t } = useTranslation();
  if (!data) return null;
  if (!data.monthly_sales) return <DashboardRefreshRequired {...cardProps} />;

  const jobsByDate = _.groupBy(data.monthly_sales, (item) => dayjs(item.date_invoiced).format("YYYY-MM-DD"));

  const listOfDays = Utils.ListOfDaysInCurrentMonth();

  const chartData = listOfDays.reduce((acc, val) => {
    //Sum up the current day.
    let dailySales;
    if (jobsByDate[val]) {
      dailySales = jobsByDate[val].reduce((dayAcc, dayVal) => {
        return dayAcc.add(Dinero((dayVal.job_totals && dayVal.job_totals.totals.subtotal) || 0));
      }, Dinero());
    } else {
      dailySales = Dinero();
    }

    const theValue = {
      date: dayjs(val).format("DD"),
      dailySales: dailySales.getAmount() / 100,
      accSales:
        acc.length > 0 ? acc[acc.length - 1].accSales + dailySales.getAmount() / 100 : dailySales.getAmount() / 100
    };

    return [...acc, theValue];
  }, []);

  return (
    <Card title={t("dashboard.titles.monthlyrevenuegraph")} {...cardProps}>
      <div style={{ height: "100%" }}>
        <ResponsiveContainer width="100%" height="100%" minHeight={100}>
          <ComposedChart data={chartData} margin={{ top: 20, right: 20, bottom: 20, left: 20 }}>
            <CartesianGrid stroke="#f5f5f5" />
            <XAxis dataKey="date" />
            <YAxis />
            <Tooltip formatter={(value) => value && value.toFixed(2)} />
            <Legend />
            <Area type="monotone" name="Accumulated Sales" dataKey="accSales" fill="#3CB371" stroke="#3CB371" />
            <Bar
              name="Daily Sales"
              dataKey="dailySales"
              //stackId="day"
              barSize={20}
              fill="#413ea0"
            />
          </ComposedChart>
        </ResponsiveContainer>
      </div>
    </Card>
  );
}

export const DashboardMonthlyRevenueGraphGql = `

`;
