import { Spin } from "antd";
import axios from "axios";
import Dinero from "dinero.js";
import { 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 = () => ({});
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) return;

    setLoading(true);
    const errorMessage = "Error encountered when contacting IntelliPay service to determine cash discounted price.";

    try {
      const { id, imexshopid, state } = bodyshop;
      const { data } = await axios.post("/intellipay/checkfee", {
        bodyshop: { id, imexshopid, state },
        amount: Dinero(amountDinero).toUnit()
      });

      if (data?.error) {
        notification.open({ type: "error", message: data.error || errorMessage });
      } else {
        setFee(data?.fee ?? 0);
      }
    } catch (error) {
      notification.open({ type: "error", message: error.response?.data?.error || errorMessage });
    } finally {
      setLoading(false);
    }
  }, [amountDinero, bodyshop, notification]);

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

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