import { Spin } from "antd";
import axios from "axios";
import Dinero from "dinero.js";
import React, { useCallback, useEffect, useState } from "react";

import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { selectBodyshop } from "../../redux/user/user.selectors";
import { useNotification } from "../../contexts/Notifications/notificationContext.jsx";

const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop
});
const mapDispatchToProps = (dispatch) => ({});
export default connect(mapStateToProps, mapDispatchToProps)(JobTotalsCashDiscount);

export function JobTotalsCashDiscount({ bodyshop, amountDinero }) {
  const [loading, setLoading] = useState(true);
  const [fee, setFee] = useState(0);
  const notification = useNotification();

  const fetchData = useCallback(async () => {
    if (amountDinero && bodyshop) {
      setLoading(true);
      let response;
      try {
        response = await axios.post("/intellipay/checkfee", {
          bodyshop: { id: bodyshop.id, imexshopid: bodyshop.imexshopid, state: bodyshop.state },
          amount: Dinero(amountDinero).toFormat("0.00")
        });

        if (response?.data?.error) {
          notification.open({
            type: "error",
            message:
              response.data?.error ||
              "Error encountered when contacting IntelliPay service to determine cash discounted price."
          });
        } else {
          setFee(response.data?.fee || 0);
        }
      } catch (error) {
        notification.open({
          type: "error",
          message:
            error.response?.data?.error ||
            "Error encountered when contacting IntelliPay service to determine cash discounted price."
        });
      } finally {
        setLoading(false);
      }
    }
  }, [amountDinero, bodyshop]);

  useEffect(() => {
    fetchData();
  }, [fetchData, bodyshop, amountDinero]);

  if (loading) return <Spin size="small" />;
  return Dinero(amountDinero)
    .add(Dinero({ amount: Math.round(fee * 100) }))
    .toFormat();
}
