import React, { useEffect } from "react";
import { Grid } from "../../../../components/grid/Grid";
import { SPACING } from "../../../../data/spacing";
import { useDispatch, useSelector } from "react-redux";
import { ProvinceSellCarcassInProvince } from "../slaughter-sell-carcass-in-province/ProvinceSellCarcassInProvince";
import { getKillhouseApprovedPriceState } from "../../../province/services/get-approved-price-state";
import { SlaughterShowProducts } from "../slaughter-show-products/SlaughterShowProducts";
import { fetchSlaughterBroadcastAndProducts } from "../../services/handle-fetch-slaughter-products";
import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith";

export const SlaughterSellCarcass = () => {
  const dispatch = useDispatch();
  const selectedSubUser = useSelector(
    (state) => state.userSlice.selectedSubUser
  );
  const { priceInfo } = useSelector((state) => state.slaughterSlice);

  const fetchData = () => {
    dispatch(
      fetchSlaughterBroadcastAndProducts({
        role_key: checkPathStartsWith("slaughter") ? selectedSubUser?.key : "",
      })
    );
    dispatch(
      getKillhouseApprovedPriceState({
        role_key: checkPathStartsWith("slaughter") ? selectedSubUser?.key : "",
      })
    );
  };

  useEffect(() => {
    fetchData();
  }, [dispatch, selectedSubUser?.key]);

  return (
    <Grid
      container
      direction="column"
      alignItems="center"
      justifyContent="space-between"
      gap={SPACING.SMALL}
      mt={SPACING.MEDIUM}
      xs={12}
    >
      <Grid container isDashboard xs={12}>
        <SlaughterShowProducts />
      </Grid>

      <ProvinceSellCarcassInProvince
        updateTable={fetchData}
        priceInfo={priceInfo}
      />
    </Grid>
  );
};
