import { Card, Input, Space, Typography } from "antd";
import axios from "axios";
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { alphaSort } from "../../../utils/sorters";
import LoadingSkeleton from "../../loading-skeleton/loading-skeleton.component";
import Dinero from "dinero.js";
import DashboardRefreshRequired from "../refresh-required.component";
import { pageLimit } from "../../../utils/config";
import ResponsiveTable from "../../responsive-table/responsive-table.component.jsx";

export default function DashboardMonthlyJobCosting({ data, ...cardProps }) {
  const { t } = useTranslation();
  const [loading, setLoading] = useState(false);
  const [costingData, setcostingData] = useState(null);
  const [searchText, setSearchText] = useState("");
  const [state, setState] = useState({
    sortedInfo: {}
  });

  useEffect(() => {
    async function getCostingData() {
      if (data?.monthly_sales) {
        setLoading(true);
        const response = await axios.post("/job/costingmulti", {
          jobids: data.monthly_sales.map((x) => x.id)
        });
        setcostingData(response.data);
        setLoading(false);
      }
    }

    getCostingData();
  }, [data]);

  if (!data) return null;
  if (!data.monthly_sales) return <DashboardRefreshRequired {...cardProps} />;
  const handleTableChange = (pagination, filters, sorter) => {
    setState({ ...state, filteredInfo: filters, sortedInfo: sorter });
  };
  const columns = [
    {
      title: t("bodyshop.fields.responsibilitycenter"),
      dataIndex: "cost_center",
      key: "cost_center",
      sorter: (a, b) => alphaSort(a.cost_center, b.cost_center),
      sortOrder: state.sortedInfo.columnKey === "cost_center" && state.sortedInfo.order
    },
    {
      title: t("jobs.labels.sales"),
      dataIndex: "sales",
      key: "sales",
      sorter: (a, b) => parseFloat(a.sales.substring(1)) - parseFloat(b.sales.substring(1)),
      sortOrder: state.sortedInfo.columnKey === "sales" && state.sortedInfo.order
    },

    {
      title: t("jobs.labels.costs"),
      dataIndex: "costs",
      key: "costs",
      sorter: (a, b) => parseFloat(a.costs.substring(1)) - parseFloat(b.costs.substring(1)),
      sortOrder: state.sortedInfo.columnKey === "costs" && state.sortedInfo.order
    },

    {
      title: t("jobs.labels.gpdollars"),
      dataIndex: "gpdollars",
      key: "gpdollars",
      sorter: (a, b) => parseFloat(a.gpdollars.substring(1)) - parseFloat(b.gpdollars.substring(1)),

      sortOrder: state.sortedInfo.columnKey === "gpdollars" && state.sortedInfo.order
    },
    {
      title: t("jobs.labels.gppercent"),
      dataIndex: "gppercent",
      key: "gppercent",
      sorter: (a, b) => parseFloat(a.gppercent.slice(0, -1) || 0) - parseFloat(b.gppercent.slice(0, -1) || 0),
      sortOrder: state.sortedInfo.columnKey === "gppercent" && state.sortedInfo.order
    }
  ];
  const filteredData =
    searchText === ""
      ? costingData?.allCostCenterData || []
      : costingData.allCostCenterData.filter((d) =>
          (d.cost_center || "").toString().toLowerCase().includes(searchText.toLowerCase())
        );

  return (
    <Card
      title={t("dashboard.titles.monthlyjobcosting")}
      extra={
        <Space wrap>
          <Input.Search
            placeholder={t("general.labels.search")}
            value={searchText}
            onChange={(e) => {
              e.preventDefault();
              setSearchText(e.target.value);
            }}
            enterButton
          />
        </Space>
      }
      {...cardProps}
    >
      <LoadingSkeleton loading={loading}>
        <div style={{ height: "100%", minHeight: 0, width: "100%", overflow: "auto" }}>
          <ResponsiveTable
            size="small"
            tableLayout="fixed"
            onChange={handleTableChange}
            pagination={{ placement: "top", defaultPageSize: pageLimit }}
            columns={columns}
            scroll={{ x: "max-content" }}
            rowKey="id"
            style={{ width: "100%" }}
            dataSource={filteredData}
            summary={() => (
              <ResponsiveTable.Summary.Row>
                <ResponsiveTable.Summary.Cell>
                  <Typography.Title level={4}>{t("general.labels.totals")}</Typography.Title>
                </ResponsiveTable.Summary.Cell>
                <ResponsiveTable.Summary.Cell>
                  {Dinero(costingData?.allSummaryData && costingData.allSummaryData.totalSales).toFormat()}
                </ResponsiveTable.Summary.Cell>
                <ResponsiveTable.Summary.Cell>
                  {Dinero(costingData?.allSummaryData && costingData.allSummaryData.totalCost).toFormat()}
                </ResponsiveTable.Summary.Cell>
                <ResponsiveTable.Summary.Cell>
                  {Dinero(costingData?.allSummaryData && costingData.allSummaryData.gpdollars).toFormat()}
                </ResponsiveTable.Summary.Cell>
                <ResponsiveTable.Summary.Cell></ResponsiveTable.Summary.Cell>
              </ResponsiveTable.Summary.Row>
            )}
          />
        </div>
      </LoadingSkeleton>
    </Card>
  );
}
