import { useEffect, useState } from "react";

import { Alert, Card } from "antd";
import axios from "axios";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { selectBodyshop } from "../../redux/user/user.selectors";
import JobCostingStatistics from "../job-costing-statistics/job-costing-statistics.component";
import LoadingSkeleton from "../loading-skeleton/loading-skeleton.component";

const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop
});

const mapDispatchToProps = () => ({});

export default connect(mapStateToProps, mapDispatchToProps)(JobCloseRoGuardProfit);

export function JobCloseRoGuardProfit({ job, bodyshop, warningCallback }) {
  const [costingData, setCostingData] = useState(null);
  const [loading, setLoading] = useState(false);
  const { t } = useTranslation();

  useEffect(() => {
    async function getData() {
      try {
        if (job.id) {
          setLoading(true);
          const { data } = await axios.post("/job/costing", { jobid: job.id });
          setCostingData(data);
        }
      } catch {
        // NO OP
      }
      setLoading(false);
    }

    getData();
  }, [job.id]);

  const enforceProfitPassword =
    parseFloat(costingData?.summaryData.gppercent) < bodyshop?.md_ro_guard?.totalgppercent_minimum;

  useEffect(() => {
    if (enforceProfitPassword && typeof warningCallback === "function") {
      warningCallback({ key: "profit", warning: t("jobs.labels.profitbypassrequired") });
    }
  }, [enforceProfitPassword, t, warningCallback]);

  if (loading || !costingData) return <LoadingSkeleton />;

  return (
    <Card title={t("jobs.labels.profits")} style={{ height: "100%" }}>
      <JobCostingStatistics summaryData={costingData?.summaryData} onlyGP />
      {enforceProfitPassword && (
        <Alert style={{ margin: "8px 0px" }} type="warning" title={t("jobs.labels.profitbypassrequired")} />
      )}
    </Card>
  );
}
