import {
  Button,
  Checkbox,
  Chip,
  FormControlLabel,
  IconButton,
  Tab,
  Tabs,
  TextField,
  Tooltip,
  Typography,
} from "@mui/material";
import VisibilityIcon from "@mui/icons-material/Visibility";
import AddCircleOutlineIcon from "@mui/icons-material/AddCircleOutline";
import EditIcon from "@mui/icons-material/Edit";
import { format } from "date-fns-jalali";
import { useContext, useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
// import { AdvancedTable } from "../../../../components/advanced-table/AdvancedTable";
import { Grid } from "../../../../components/grid/Grid";
// import { vetFarmGetAllocatedService } from "../../services/vet-farm-get-allocated";
import { VetFarmOperationRow } from "../vet-farm-operation-row/VetFarmOperationRow";
import { DatePicker } from "@mui/x-date-pickers";
import moment from "moment/moment";
import { SPACING } from "../../../../data/spacing";
import { AppContext } from "../../../../contexts/AppContext";
import axios from "axios";
import { SiGooglemessages } from "react-icons/si";
import { RiFileExcel2Fill, RiSearchLine } from "react-icons/ri";

import {
  DRAWER,
  LOADING_END,
  LOADING_START,
  OPEN_MODAL,
} from "../../../../lib/redux/slices/appSlice";
import { vetFarmGetDeletedBarsService } from "../../services/vet-farm-get-deleted-bars";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
// import { getFaUserRole } from "../../../../utils/getFaUserRole";
import { VetFarmDeletedBars } from "../vet-farm-deleted-bars/VetFarmDeletedBars";
import { EnterAggregateLoadInformation } from "../../../slaughter-house/components/enter-aggregate-load-information/EnterAggregateLoadInformation";
import { SlaughterManageBars } from "../../../slaughter-house/components/slaughter-manage-bars/SlaughterManageBars";
import { VetFarmSubmitContradicts } from "../vet-farm-submit-contradicts/VetFarmSubmitContradicts";
import { VetFarmEditTrafficCode } from "../vet-farm-edit-traffic-code/VetFarmEditTrafficCode";
import { VetFarmEditQuarantineCodeState } from "../vet-farm-edit-quarantine-code-state/VetFarmEditQuarantineCodeState";
import { VetFarmOutOfProvince } from "../vet-farm-sale-out-of-province/VetFarmOutOfProvince";
import { formatJustDate, formatTime } from "../../../../utils/formatTime";
import { vetFarmGetBarsOverview } from "../../services/vet-farm-get-bars-overview";
import { ChainBarManagement } from "../../../province/components/chain-bar-management/ChainBarManagement";
import ShowImage from "../../../../components/show-image/ShowImage";
import { VetFarmOperationOptions } from "../vet-farm-operations-options/VetFarmOperationOptions";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { SlaughterOutProvinceBars } from "../../../slaughter-house/components/slaughter-out-province-bars/SlaughterOutProvinceBars";
import { provincePolicyGetAggregateBarInfoAllowStatus } from "../../../province/services/province-policy-get-aggregate-bar-info-allow-state";
import { VetFarmAggregateBars } from "../vet-farm-aggregate-bars/VetFarmAggregateBars";
import { vetFarmDeleteAggregateBarService } from "../../services/vet-farm-delete-aggregate-bar";
import RefreshIcon from "@mui/icons-material/Refresh";
import { SimpleTable } from "../../../../components/simple-table/SimpleTable";
import { SlaughterEnterNoneReciept } from "../../../slaughter-house/components/slaughter-enter-none-receipt/SlaughterEnterNoneReciept";
import SupporterSettlement from "../../../supporter/components/SupporterSettlement";

export const VetFarmOperation = () => {
  const [data, setData] = useState([]);
  const [totalRows, setTotalRows] = useState(0);
  const [perPage, setPerPage] = useState(10);
  const [selectedTab, setSelectedTab] = useState(0);
  const [tableData, setTableData] = useState([]);
  const [aggregates, setAggregates] = useState([]);
  const [page, setPage] = useState(1);
  const [aggregateStatus, setAggregateStatus] = useState(false);
  const [hasDocumentState, setHasDocumentState] = useState(false);
  const [textValue, setTextValue] = useState("");
  const [has500Error, setHas500Error] = useState(false);

  const dispatch = useDispatch();

  const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] =
    useContext(AppContext);
  const userInfo = useSelector((state) => state.userSlice);
  const { vetFarmBarsOverview } = useSelector((state) => state.vetFarmSlice);

  useEffect(() => {
    const currentDate = moment(new Date()).format("YYYY-MM-DD");
    setSelectedDate1(currentDate);
    setSelectedDate2(currentDate);
  }, []);
  // const { vetFarmGetDeletedBars } = useSelector((state) => state.vetFarmSlice);

  const handleTabChange = (event, newValue) => {
    setSelectedTab(newValue);
  };

  const handleChangeDocumentState = () => {
    setHasDocumentState(!hasDocumentState);
  };

  // const [dataTable, setDataTable] = useState([]);
  // const [dataDeletedTable, setDataDeletedTable] = useState([]);

  const information = () => {
    if (getRoleFromUrl() !== "VetFarm") {
      return ["گزارش اختلاف فارم"];
    } else {
      return [];
    }
  };

  const renderReportCell = (item, i) => {
    if (getRoleFromUrl() === "VetFarm") {
      return [];
    }

    return item?.priceRegisterDate
      ? [
          <Tooltip key={i} title="مشاهده گزارش" placement="top">
            <IconButton
              color="primary"
              size="small"
              onClick={() => {
                dispatch(
                  DRAWER({
                    top: !(window.innerWidth <= 600),
                    bottom: window.innerWidth <= 600,
                    title: "گزارش ",
                    content: (
                      <SimpleTable
                        columns={[
                          "ثبت کننده ",
                          "تاریخ ثبت",
                          "ویرایش کننده",
                          "تاریخ ویرایش",
                          "نوع تسویه",
                          "قیمت",
                          "توضیحات",
                          "سند",
                        ]}
                        data={[
                          [
                            item?.priceRegisterar,
                            formatJustDate(item?.priceRegisterDate),
                            item?.priceEditor,
                            formatJustDate(item?.priceEditorDate),
                            item?.settlementType === "cash"
                              ? "نقدی"
                              : "مدت دار",
                            item?.price,
                            item?.description,
                            <Grid
                              key={i}
                              container
                              xs={12}
                              justifyContent="center"
                              gap={1}
                            >
                              <ShowImage key={i} src={item?.image} />,
                            </Grid>,
                          ],
                        ]}
                      />
                    ),
                  })
                );
              }}
            >
              <VisibilityIcon fontSize="small" />
            </IconButton>
          </Tooltip>,
        ]
      : ["بدون گزارش"];
  };

  const getItemState = (item) => {
    let state = "";
    let color = "default";

    if (item.trash === true) {
      state = "حذف شده";
      color = "error";
    } else if (item?.wareHouseConfirmation) {
      state = "ورود به انبار";
      color = "success";
    } else if (item?.assignmentStateArchive !== "pending") {
      state = "ثبت اطلاعات بار";
      color = "info";
    } else if (item.vetState === "accepted") {
      state = "تایید تخلیه";
      color = "success";
    } else if (item.vetState === "pending") {
      state = "در انتظار تخلیه";
      color = "warning";
    } else {
      state = "نامشخص";
    }

    return (
      <Chip
        label={state}
        color={color}
        size="small"
        variant="outlined"
        sx={{ minWidth: 90, justifyContent: "center" }}
      />
    );
  };

  const fetchApiData = async (page) => {
    // Prevent request if there was a 500 error
    if (has500Error) {
      return;
    }

    dispatch(LOADING_START());
    try {
      const response = await axios.get(
        `kill_house_request_bar_management/?check&search=filter&value=${textValue}&role=${getRoleFromUrl()}&date1=${selectedDate1}&date2=${selectedDate2}&page=${page}&page_size=${perPage}&without_quarantine_code_state=${hasDocumentState}`
      );
      // Reset error state on successful response
      setHas500Error(false);
      setData(response.data?.results || []);
      setTotalRows(response.data?.count || 0);
    } catch (error) {
      console.error("Error fetching data:", error);
      const errorMessage = error?.message || "";
      const status = error?.response?.status;
      const is500Error = errorMessage.includes("500") || status === 500;

      if (is500Error) {
        setHas500Error(true);
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: "مشکلی در دریافت اطلاعات پیش آمده است!",
          severity: "error",
        });
      } else {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: "مشکلی در دریافت اطلاعات پیش آمده است!",
          severity: "error",
        });
      }
      setData([]);
      setTotalRows(0);
    } finally {
      dispatch(LOADING_END());
    }
  };

  const handlePageChange = (page) => {
    fetchApiData(page);
    setPage(page);
  };

  const handlePerRowsChange = (perRows) => {
    setPerPage(perRows);
    setPage(1);
  };

  const updateTable = () => {
    fetchApiData(page !== 0 ? page : 1);
  };

  useEffect(() => {
    // Prevent request if there was a 500 error
    if (has500Error) {
      return;
    }

    // dispatch(vetFarmGetAllocatedService({ selectedDate1, selectedDate2 }));
    fetchApiData(page);
    dispatch(vetFarmGetDeletedBarsService({ selectedDate1, selectedDate2 }))
      .then((r) => {
        if (r?.error) {
          const errorMessage = r.error?.message || "";
          const is500Error =
            errorMessage.includes("500") ||
            r.error?.status === 500 ||
            r.error?.statusCode === 500;

          if (is500Error) {
            setHas500Error(true);
            openNotif({
              vertical: "top",
              horizontal: "center",
              msg: "مشکلی در دریافت اطلاعات پیش آمده است!",
              severity: "error",
            });
          }
        } else {
          setHas500Error(false);
        }
      })
      .catch((error) => {
        console.error("Error fetching deleted bars:", error);
        const errorMessage = error?.message || "";
        const status = error?.response?.status;
        const is500Error = errorMessage.includes("500") || status === 500;

        if (is500Error) {
          setHas500Error(true);
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "مشکلی در دریافت اطلاعات پیش آمده است!",
            severity: "error",
          });
        }
      });
    dispatch(
      vetFarmGetBarsOverview({
        selectedDate1,
        selectedDate2,
        textValue,
        hasDocumentState,
      })
    )
      .then((r) => {
        if (r?.error) {
          const errorMessage = r.error?.message || "";
          const is500Error =
            errorMessage.includes("500") ||
            r.error?.status === 500 ||
            r.error?.statusCode === 500;

          if (is500Error) {
            setHas500Error(true);
            openNotif({
              vertical: "top",
              horizontal: "center",
              msg: "مشکلی در دریافت اطلاعات پیش آمده است!",
              severity: "error",
            });
          }
        } else {
          setHas500Error(false);
        }
      })
      .catch((error) => {
        console.error("Error fetching bars overview:", error);
        const errorMessage = error?.message || "";
        const status = error?.response?.status;
        const is500Error = errorMessage.includes("500") || status === 500;

        if (is500Error) {
          setHas500Error(true);
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "مشکلی در دریافت اطلاعات پیش آمده است!",
            severity: "error",
          });
        }
      });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [selectedDate1, selectedDate2, hasDocumentState, perPage]);

  // Reset error state when dates or filters change
  useEffect(() => {
    setHas500Error(false);
  }, [selectedDate1, selectedDate2, hasDocumentState, textValue]);

  useEffect(() => {
    fetchApiData(1);
    dispatch(provincePolicyGetAggregateBarInfoAllowStatus())
      .then((r) => {
        if (r?.error) {
          const errorMessage = r.error?.message || "";
          const is500Error =
            errorMessage.includes("500") ||
            r.error?.status === 500 ||
            r.error?.statusCode === 500;

          if (is500Error) {
            setHas500Error(true);
            openNotif({
              vertical: "top",
              horizontal: "center",
              msg: "مشکلی در دریافت اطلاعات پیش آمده است!",
              severity: "error",
            });
          }
          setAggregateStatus(false);
        } else if (r?.payload?.data) {
          setHas500Error(false);
          setAggregateStatus(r.payload.data);
        } else {
          setAggregateStatus(false);
        }
      })
      .catch((error) => {
        console.error("Error fetching aggregate status:", error);
        const errorMessage = error?.message || "";
        const status = error?.response?.status;
        const is500Error = errorMessage.includes("500") || status === 500;

        if (is500Error) {
          setHas500Error(true);
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "مشکلی در دریافت اطلاعات پیش آمده است!",
            severity: "error",
          });
        }
        setAggregateStatus(false);
      });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  useEffect(() => {
    if (!data || !Array.isArray(data)) {
      setTableData([]);
      return;
    }

    const d = data.map((item, i) => {
      return [
        <Grid
          id="merge"
          container
          key={i}
          alignItems="center"
          justifyContent="center"
          style={{
            minWidth:
              getRoleFromUrl() === "VetFarm" ||
              getRoleFromUrl() === "AdminX" ||
              getRoleFromUrl() === "SuperAdmin"
                ? "100px"
                : "50px",
          }}
        >
          {aggregateStatus?.allow &&
            (getRoleFromUrl() === "VetFarm" ||
              getRoleFromUrl() === "AdminX" ||
              getRoleFromUrl() === "SuperAdmin") && (
              <Grid item>
                {item?.clearanceCode && item?.aggregateCode ? (
                  <FormControlLabel
                    control={
                      <Tooltip title="حذف از ادغام" placement="top">
                        <IconButton
                          color="error"
                          disabled={
                            data?.filter(
                              (option) =>
                                option.aggregateCode === item?.aggregateCode
                            ).length < 3
                          }
                          key={i}
                          onClick={() => {
                            dispatch(
                              vetFarmDeleteAggregateBarService({
                                kill_house_request_key: item?.key,
                              })
                            )
                              .then((r) => {
                                if (r?.error || r?.payload?.error) {
                                  const errorMsg =
                                    r.payload?.error || r.error?.message || "";
                                  const is500Error =
                                    errorMsg.includes("500") ||
                                    r.error?.status === 500 ||
                                    r.error?.statusCode === 500;

                                  if (is500Error) {
                                    setHas500Error(true);
                                    openNotif({
                                      vertical: "top",
                                      horizontal: "center",
                                      msg: "مشکلی در دریافت اطلاعات پیش آمده است!",
                                      severity: "error",
                                    });
                                  } else {
                                    openNotif({
                                      vertical: "top",
                                      horizontal: "center",
                                      msg:
                                        errorMsg ||
                                        "مشکلی در حذف از ادغام پیش آمده است!",
                                      severity: "error",
                                    });
                                  }
                                } else {
                                  // Reset error state on successful response
                                  setHas500Error(false);
                                  setAggregates([]);
                                  updateTable();
                                  openNotif({
                                    vertical: "top",
                                    horizontal: "center",
                                    msg: "عملیات با موفقیت انجام شد.",
                                    severity: "success",
                                  });
                                }
                              })
                              .catch((error) => {
                                console.error(
                                  "Error deleting aggregate bar:",
                                  error
                                );
                                const errorMessage = error?.message || "";
                                const status = error?.response?.status;
                                const is500Error =
                                  errorMessage.includes("500") ||
                                  status === 500;

                                if (is500Error) {
                                  setHas500Error(true);
                                  openNotif({
                                    vertical: "top",
                                    horizontal: "center",
                                    msg: "مشکلی در دریافت اطلاعات پیش آمده است!",
                                    severity: "error",
                                  });
                                } else {
                                  openNotif({
                                    vertical: "top",
                                    horizontal: "center",
                                    msg: "مشکلی در حذف از ادغام پیش آمده است!",
                                    severity: "error",
                                  });
                                }
                              });
                          }}
                        >
                          <RefreshIcon />
                        </IconButton>
                      </Tooltip>
                    }
                  />
                ) : (
                  <FormControlLabel
                    control={
                      <Checkbox
                        disabled={
                          (aggregates.length &&
                            !(
                              aggregates[0]?.poultryRequest?.poultry
                                ?.unitName ===
                                item?.poultryRequest?.poultry?.unitName &&
                              aggregates[0]?.killhouseUser?.name ===
                                item?.killhouseUser?.name
                            )) ||
                          (item?.clearanceCode && item?.aggregateCode)
                        }
                        checked={
                          aggregates.filter(
                            (option) => option?.barCode === item?.barCode
                          ).length > 0
                        }
                        onChange={() => {
                          if (
                            aggregates.some(
                              (option) => option?.barCode === item?.barCode
                            )
                          ) {
                            setAggregates(
                              aggregates.filter(
                                (option) => option?.barCode !== item?.barCode
                              )
                            );
                          } else {
                            if (item?.aggregateCode) {
                              setAggregates(
                                data?.filter(
                                  (option) =>
                                    option?.aggregateCode ===
                                    item?.aggregateCode
                                )
                              );
                            } else {
                              setAggregates([...aggregates, item]);
                            }
                          }
                        }}
                        color="primary"
                      />
                    }
                  />
                )}
              </Grid>
            )}
          <Grid item>{page === 1 ? i + 1 : i + (perPage * page) / 2 + 1}</Grid>
        </Grid>,
        item?.aggregateCode ? (
          <Tooltip title="مشاهده بارها" placement="top">
            {" "}
            <Typography
              variant="body2"
              color="primary"
              style={{ cursor: "pointer" }}
              onClick={() => {
                if (aggregateValidationHasError()) {
                  openNotif({
                    vertical: "top",
                    horizontal: "center",
                    msg: `فقط بارهای با خریدار و مرغدار یکسان و با مجموع تعداد حداکثر ${aggregateStatus?.limitation} میتوانید ادغام کنید!`,
                    severity: "error",
                  });
                } else {
                  dispatch(
                    OPEN_MODAL({
                      title: "مشاهده بارهای ادغام شده",
                      content: (
                        <VetFarmAggregateBars
                          toShow
                          setAggregates={setAggregates}
                          bars={data?.filter(
                            (option) =>
                              option?.aggregateCode === item?.aggregateCode
                          )}
                        />
                      ),
                    })
                  );
                }
              }}
            >
              دارد
            </Typography>
          </Tooltip>
        ) : (
          <Typography variant="body2">ندارد</Typography>
        ),
        getItemState(item),
        <Typography
          key={i}
          style={{ fontSize: "13px", color: item?.trash ? "red" : "black" }}
        >
          {item?.barCode || ""}
          {item?.priceRegisterDate ? "✉️" : ""}
        </Typography>,
        item?.createDate ? formatTime(item.createDate) : "-",
        item?.poultryRequest?.freezing
          ? "انجماد"
          : item?.poultryRequest?.export
          ? "صادرات"
          : "عادی",
        item?.poultryRequest?.freeSaleInProvince ? "آزاد" : "دولتی",
        `${item?.killhouseUser?.name || ""} (${
          item?.killhouseUser?.killHouseOperator?.user?.mobile || ""
        })`,
        item?.killer
          ? `${item.killer?.name || ""} (${
              item.killer?.killHouseOperator?.user?.mobile || ""
            })`
          : "-",
        `${item?.poultryRequest?.poultry?.user?.fullname || ""} (${
          item?.poultryRequest?.poultry?.user?.mobile || ""
        })`,
        item?.poultryRequest?.poultry?.unitName || "",
        item?.quantity ? item.quantity.toLocaleString() : "0",
        item?.weightInfo?.weight
          ? item.weightInfo.weight.toLocaleString()
          : "0",
        <>
          <VetFarmEditTrafficCode
            updateTable={updateTable}
            killHouseRequestKey={item.key}
            trafficCode={item?.trafficCode}
            isEditable={
              (getRoleFromUrl() === "ProvinceOperator" ||
                getRoleFromUrl() === "SuperAdmin" ||
                getRoleFromUrl() === "VetFarm" ||
                getRoleFromUrl() === "AdminX" ||
                getRoleFromUrl() === "CityVet" ||
                getRoleFromUrl() === "Supporter") &&
              item.trash !== true &&
              item.assignmentStateArchive === "pending" &&
              !item?.clearanceCode
            }
          />
        </>,
        item?.amount ? item.amount.toLocaleString() + " ﷼" : "0 ﷼",

        <VetFarmOperationRow
          key={i}
          item={item}
          updateTable={updateTable}
          isEditable={
            getRoleFromUrl() === "VetFarm" ||
            getRoleFromUrl() === "ProvinceOperator" ||
            getRoleFromUrl() === "SuperAdmin" ||
            getRoleFromUrl() === "CityVet" ||
            getRoleFromUrl() === "AdminX" ||
            getRoleFromUrl() === "Supporter"
          }
        />,
        <>
          {item?.quarantineQuantity ? (
            <VetFarmEditQuarantineCodeState
              code={item?.quarantineQuantity}
              updateTable={updateTable}
              item={item}
            />
          ) : (
            <>
              {item?.quarantineCodeState &&
                (item?.quarantineCodeState === "contradiction"
                  ? "مغایرت کد رهگیری"
                  : item?.quarantineCodeState === "noclearance"
                  ? "فاقد کد رهگیری"
                  : item?.quarantineCodeState === "merge"
                  ? "ادغام"
                  : "عدم تایید راهداری")}

              {(getRoleFromUrl() === "SuperAdmin" ||
                getRoleFromUrl() === "AdminX") && (
                <Tooltip
                  title={
                    item?.quarantineCodeState
                      ? "ویرایش تعداد ثبت شده در قرنطینه"
                      : "ثبت تعداد در قرنطینه"
                  }
                  placement="top"
                >
                  <IconButton
                    color="primary"
                    onClick={() => {
                      dispatch(
                        OPEN_MODAL({
                          title: "تعداد ثبت شده در قرنطینه",
                          content: (
                            <VetFarmSubmitContradicts
                              item={item}
                              updateTable={updateTable}
                            />
                          ),
                        })
                      );
                    }}
                  >
                    {item?.quarantineCodeState ? (
                      <EditIcon fontSize="small" />
                    ) : (
                      <AddCircleOutlineIcon fontSize="small" />
                    )}
                  </IconButton>
                </Tooltip>
              )}
            </>
          )}
        </>,

        // item?.realAddCar?.driver
        //   ? `${item?.realAddCar?.driver?.typeCar} (${
        //       item?.realAddCar?.driver?.pelak
        //         ? item?.realAddCar?.driver?.pelak
        //         : "نامشخص"
        //     })`
        //   : "-",
        `${item?.addCar?.driver?.typeCar || ""} ${
          item?.addCar?.driver?.pelak || ""
        }`,
        `${item?.addCar?.driver?.driverName || ""} (${
          item?.addCar?.driver?.driverMobile || ""
        })`,
        item?.poultryRequest?.chickenBreed || "",
        item?.poultryRequest?.age
          ? item.poultryRequest.age.toLocaleString()
          : "0",
        item?.weightInfo?.indexWeight
          ? item.weightInfo.indexWeight.toLocaleString()
          : "0",
        ...(getRoleFromUrl() === "VetFarm"
          ? []
          : [
              (item?.poultryRequest?.amount
                ? item.poultryRequest.amount.toLocaleString()
                : "0") + " ﷼",
              (item?.weightInfo?.killHousePrice
                ? item.weightInfo.killHousePrice.toLocaleString()
                : "0") + " ﷼",
              (item?.price ? item.price.toLocaleString() : "0") + "﷼",
            ]),
        item?.vetFarm?.vet?.user?.fullname
          ? item.vetFarm.vet.user.fullname +
            `(${item?.vetFarm?.vet?.user?.mobile || ""})`
          : "فاقد دامپزشک",
        item?.killPlace || "-",
        item?.poultryRequest?.poultry?.address?.city?.name || "",
        item?.poultryRequest.sendDate
          ? format(new Date(item?.poultryRequest.sendDate), "yyyy/MM/dd")
          : "-",
        item?.poultryRequest.orderCode,
        ...(getRoleFromUrl() === "VetFarm"
          ? []
          : [
              <Typography key={i} variant="body2">
                {item?.barDocumentStatus ? (
                  <Tooltip
                    title={item?.barDocumentDescription || "بدون توضیحات"}
                    arrow
                    placement="top"
                  >
                    <Typography
                      variant="body2"
                      sx={{
                        cursor: item?.barDocumentDescription
                          ? "pointer"
                          : "default",
                      }}
                    >
                      {item?.barDocumentStatus?.title || "-"}
                    </Typography>
                  </Tooltip>
                ) : (
                  <Typography variant="body2">-</Typography>
                )}
              </Typography>,
              <ShowImage key={i} src={item?.assignmentInfo?.imageWithBar} />,
              item?.acceptedRealQuantity
                ? item.acceptedRealQuantity.toLocaleString()
                : "0",
              item?.acceptedRealWeight
                ? item.acceptedRealWeight.toLocaleString()
                : "0",
              item?.weightInfo?.finalIndexWeight
                ? item.weightInfo.finalIndexWeight.toLocaleString()
                : "0",
              item?.wareHouseAcceptedRealQuantity
                ? item.wareHouseAcceptedRealQuantity.toLocaleString()
                : "0",
              item?.wareHouseAcceptedRealWeight
                ? item.wareHouseAcceptedRealWeight.toLocaleString()
                : "0",
              item?.weightLoss ? item.weightLoss.toLocaleString() : "0",
            ]),
        ...renderReportCell(item, i),
        <VetFarmOperationOptions
          key={i}
          item={item}
          updateTable={updateTable}
        />,
      ];
    });

    setTableData(d);
  }, [data, aggregates]);

  const [openNotif] = useContext(AppContext);

  const handleDateChange1 = (date) => {
    setSelectedDate1(date);
  };

  const handleDateChange2 = (date) => {
    setSelectedDate2(date);
  };

  const handleTextChange = (event) => {
    setTextValue(event.target.value);
  };

  const handleSubmit = async (event) => {
    event.preventDefault();
    // Reset error state on manual submit (user retry)
    setHas500Error(false);
    dispatch(LOADING_START());

    try {
      const response = await axios.get(
        `kill_house_request_bar_management/?check&role=${getRoleFromUrl()}&search=filter&value=${textValue}&date1=${selectedDate1}&date2=${selectedDate2}&page=${1}&page_size=${perPage}&without_quarantine_code_state=${hasDocumentState}`
      );
      // Reset error state on successful response
      setHas500Error(false);
      setData(response.data?.results || []);
      setTotalRows(response.data?.count || 0);
      dispatch(LOADING_END());
    } catch (error) {
      console.error("Error fetching data:", error);
      const errorMessage = error?.message || "";
      const status = error?.response?.status;
      const is500Error = errorMessage.includes("500") || status === 500;

      if (is500Error) {
        setHas500Error(true);
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: "مشکلی در دریافت اطلاعات پیش آمده است!",
          severity: "error",
        });
      } else {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: "مشکلی در دریافت اطلاعات پیش آمده است!",
          severity: "error",
        });
      }
      setData([]);
      setTotalRows(0);
      dispatch(LOADING_END());
    }
    dispatch(
      vetFarmGetBarsOverview({ selectedDate1, selectedDate2, textValue })
    )
      .then((r) => {
        if (r?.error) {
          const errorMessage = r.error?.message || "";
          const is500Error =
            errorMessage.includes("500") ||
            r.error?.status === 500 ||
            r.error?.statusCode === 500;

          if (is500Error) {
            setHas500Error(true);
            openNotif({
              vertical: "top",
              horizontal: "center",
              msg: "مشکلی در دریافت اطلاعات پیش آمده است!",
              severity: "error",
            });
          }
        } else {
          setHas500Error(false);
        }
      })
      .catch((error) => {
        console.error("Error fetching bars overview:", error);
        const errorMessage = error?.message || "";
        const status = error?.response?.status;
        const is500Error = errorMessage.includes("500") || status === 500;

        if (is500Error) {
          setHas500Error(true);
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "مشکلی در دریافت اطلاعات پیش آمده است!",
            severity: "error",
          });
        }
      });
  };

  useEffect(() => {
    if (selectedTab === 0) {
      fetchApiData(1);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [selectedDate1, selectedDate2, hasDocumentState, selectedTab]);

  const ExcelExportButton = ({ pathLink, name, isSlaughter = false }) => {
    const date = isSlaughter
      ? `date1=${selectedDate1}&date2=${selectedDate2}`
      : `start=${selectedDate1}&end=${selectedDate2}`;

    return (
      <Grid
        container
        justifyContent="center"
        alignItems="center"
        direction="column"
        sx={{
          border: "1px solid #E6E6E6",
          borderRadius: "8px",
          padding: "16px",
          position: "relative",
          width: "160px",
          height: "160px",
          boxSizing: "border-box",
          cursor: "pointer",
          backgroundColor: "#FCFCFC",
          "&:hover": {
            boxShadow: "0px 4px 12px rgba(0, 0, 0, 0.1)",
            backgroundColor: "#F5F9FF",
            "& .MuiTypography-body2": {
              color: "#2D5FFF",
            },
          },
        }}
        onClick={() => {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "فایل اکسل در حال دانلود می باشد، این علمیات ممکن است زمان بر باشد لطفا صبر کنید.",
            severity: "success",
          });
          const link = `${axios.defaults.baseURL}${pathLink}/?${date}&key=${
            userInfo?.userProfile?.key || ""
          }&role=${getRoleFromUrl()}&search=filter&value=${textValue || ""}`;
          window.location.href = link;
        }}
      >
        <Grid
          sx={{
            zIndex: "10",
            color: "white",
            width: "60px",
            height: "60px",
            position: "absolute",
            top: "-30px",
            backgroundColor: "#2D5FFF",
            borderRadius: "50%",
            "&:hover": {
              backgroundColor: "#1446E5",
            },
          }}
          variant="contained"
          size="large"
          pt={"10%"}
        >
          <RiFileExcel2Fill size={24} />
        </Grid>
        <Typography
          variant="body2"
          sx={{
            textAlign: "center",
            marginTop: "16px",
            transition: "color 0.2s ease",
          }}
        >
          {name}
        </Typography>
      </Grid>
    );
  };

  const ProvinceOperatorButtons = ({ openNotif }) => {
    const [isActiveOutProvinceMessage, setIsActiveOutProvinceMessage] =
      useState(false);
    const [isActiveInsideProvinceMessage, setIsActiveInsideProvinceMessage] =
      useState(false);

    return (
      <>
        {/* Out of Province Message */}
        <Grid
          container
          justifyContent="center"
          alignItems="center"
          direction="column"
          sx={{
            border: "1px solid #E6E6E6",
            borderRadius: "8px",
            padding: "16px",
            position: "relative",
            width: "160px",
            height: "160px",
            boxSizing: "border-box",
            cursor: "pointer",
            backgroundColor: "#FCFCFC",
          }}
        >
          <Tooltip title="ارسال پیام بارهای خارج استان در ایتا" placement="top">
            <Button
              sx={{
                width: "60px",
                position: "absolute",
                top: "-30px",
                backgroundColor: "#2D5FFF",
                border: "1px solid #E6E6E6",
                borderRadius: "50%",
                "&:hover": {
                  backgroundColor: "#1446E5",
                },
              }}
              variant="contained"
              color="error"
              size="large"
              disabled={isActiveOutProvinceMessage}
              onClick={async () => {
                setIsActiveOutProvinceMessage(true);
                try {
                  await axios.get("bot_eitaa_free_bar");
                  openNotif({
                    vertical: "top",
                    horizontal: "center",
                    msg: "پیام با موفقیت ارسال شد!",
                    severity: "success",
                  });
                } catch (error) {
                  console.error("Error sending message:", error);
                  const errorMessage = error?.message || "";
                  const status = error?.response?.status;
                  const is500Error =
                    errorMessage.includes("500") || status === 500;

                  openNotif({
                    vertical: "top",
                    horizontal: "center",
                    msg: is500Error
                      ? "مشکلی در دریافت اطلاعات پیش آمده است!"
                      : "مشکلی در ارسال پیام پیش آمده است!",
                    severity: "error",
                  });
                } finally {
                  setIsActiveOutProvinceMessage(false);
                }
              }}
            >
              <SiGooglemessages size={40} />
            </Button>
          </Tooltip>
          <Typography
            variant="body2"
            sx={{
              textAlign: "center",
              marginTop: "16px",
            }}
          >
            پیام بار خارج استان
          </Typography>
        </Grid>

        {/* In Province Message */}
        <Grid
          container
          justifyContent="center"
          alignItems="center"
          direction="column"
          sx={{
            border: "1px solid #E6E6E6",
            borderRadius: "8px",
            padding: "16px",
            position: "relative",
            width: "160px",
            height: "160px",
            boxSizing: "border-box",
          }}
        >
          <Tooltip title="ارسال پیام بارهای داخل استان در ایتا" placement="top">
            <Button
              sx={{
                width: "60px",
                position: "absolute",
                top: "-30px",
                backgroundColor: "#2D5FFF",
                border: "1px solid #E6E6E6",
                borderRadius: "50%",
                "&:hover": {
                  backgroundColor: "#1446E5",
                },
              }}
              variant="contained"
              color="success"
              size="large"
              disabled={isActiveInsideProvinceMessage}
              onClick={async () => {
                setIsActiveInsideProvinceMessage(true);
                try {
                  await axios.get("bot_eitaa_for_bar");
                  openNotif({
                    vertical: "top",
                    horizontal: "center",
                    msg: "پیام با موفقیت ارسال شد!",
                    severity: "success",
                  });
                } catch (error) {
                  console.error("Error sending message:", error);
                  const errorMessage = error?.message || "";
                  const status = error?.response?.status;
                  const is500Error =
                    errorMessage.includes("500") || status === 500;

                  openNotif({
                    vertical: "top",
                    horizontal: "center",
                    msg: is500Error
                      ? "مشکلی در دریافت اطلاعات پیش آمده است!"
                      : "مشکلی در ارسال پیام پیش آمده است!",
                    severity: "error",
                  });
                } finally {
                  setIsActiveInsideProvinceMessage(false);
                }
              }}
            >
              <SiGooglemessages size={40} />
            </Button>
          </Tooltip>
          <Typography
            variant="body2"
            sx={{
              textAlign: "center",
              marginTop: "16px",
            }}
          >
            پیام بار داخل استان
          </Typography>
        </Grid>
      </>
    );
  };

  const tableTitle = (
    <Grid
      container
      justifyContent="center"
      spacing={{ xs: 3, sm: 2, md: 1, lg: 0 }}
      gap="20px"
      xs={12}
    >
      {getRoleFromUrl() !== "ProvinceOperator" && (
        <Grid
          container
          alignItems="center"
          justifyContent="center"
          gap={2}
          xs={12}
          sx={{ py: 1 }}
          mt={3}
        >
          <ExcelExportButton name="بارهای داخل استان" pathLink={"bar_excel"} />

          {getRoleFromUrl() !== "VetFarm" &&
            getRoleFromUrl() !== "CityPoultry" && (
              <ExcelExportButton
                name="گزارش جامع"
                pathLink={"detail_of_killing_excel"}
                isSlaughter
              />
            )}

          {(getRoleFromUrl() === "ProvinceOperator" ||
            getRoleFromUrl() === "ProvinceSupervisor" ||
            getRoleFromUrl() === "SuperAdmin" ||
            getRoleFromUrl() === "Supporter" ||
            getRoleFromUrl() === "AdminX" ||
            getRoleFromUrl() === "VetSupervisor") && (
            <ExcelExportButton
              name="پایش کشتارگاه"
              pathLink={"comprehensive_report_of_the_slaughterhouse_excel"}
              isSlaughter
            />
          )}

          {(getRoleFromUrl() === "ProvinceOperator" ||
            getRoleFromUrl() === "ProvinceSupervisor" ||
            getRoleFromUrl() === "SuperAdmin" ||
            getRoleFromUrl() === "Supporter" ||
            getRoleFromUrl() === "AdminX" ||
            getRoleFromUrl() === "VetSupervisor") && (
            <ExcelExportButton
              name="عملکرد کشتارگاه ها"
              pathLink={"from_allocation_to_distribution_excel"}
              isSlaughter
            />
          )}

          {getRoleFromUrl() !== "CityPoultry" &&
            getRoleFromUrl() !== "VetFarm" && (
              <ExcelExportButton
                name="پایش بارها"
                pathLink={"monitor_loads_excel"}
                isSlaughter
              />
            )}

          {getRoleFromUrl() === "ProvinceOperator" && (
            <ProvinceOperatorButtons openNotif={openNotif} />
          )}
        </Grid>
      )}

      <Grid
        container
        direction="column"
        alignItems="flex-start"
        gap={SPACING.SMALL}
        xs={12}
        mt={{
          xs: 2,
          md: 0,
        }}
      >
        <Typography>مدیریت بارها</Typography>
        <Grid
          container
          justifyContent="flex-start"
          alignItems="center"
          direction="row"
          style={{ width: "100%" }}
          gap={2}
        >
          <DatePicker
            label="از تاریخ"
            id="date"
            renderInput={(params) => (
              <TextField sx={{ width: "150px" }} {...params} />
            )}
            value={selectedDate1}
            onChange={(e) => {
              handleDateChange1(moment(e).format("YYYY-MM-DD"));
            }}
          />
          <DatePicker
            label="تا تاریخ"
            id="date"
            renderInput={(params) => (
              <TextField sx={{ width: "150px" }} {...params} />
            )}
            value={selectedDate2}
            onChange={(e) => {
              handleDateChange2(moment(e).format("YYYY-MM-DD"));
            }}
          />
          <form onSubmit={handleSubmit}>
            <TextField
              autoComplete="off"
              size="small"
              label="جستجو"
              variant="outlined"
              style={{ width: 250 }}
              onChange={handleTextChange}
            />
            <Button
              // disabled={!textValue}
              type="submit"
              onClick={handleSubmit}
              endIcon={<RiSearchLine />}
            >
              جستجو
            </Button>
          </form>
          {(getRoleFromUrl() === "SuperAdmin" ||
            getRoleFromUrl() === "Supporter" ||
            getRoleFromUrl() === "AdminX") && (
            <FormControlLabel
              control={
                <Checkbox
                  checked={hasDocumentState}
                  onChange={handleChangeDocumentState}
                  name="item4"
                />
              }
              label="بدون وضعیت قرنطینه"
            />
          )}
        </Grid>
      </Grid>
    </Grid>
  );

  let tabs;

  if (
    getRoleFromUrl() === "ProvinceOperator" ||
    getRoleFromUrl() === "SuperAdmin" ||
    getRoleFromUrl() === "CityOperator" ||
    getRoleFromUrl() === "AdminX" ||
    getRoleFromUrl() === "Supporter"
  ) {
    tabs = (
      <Tabs
        scrollButtons="auto"
        variant="scrollable"
        allowScrollButtonsMobile
        value={selectedTab}
        onChange={handleTabChange}
      >
        <Tab label="کشتار داخل استان" value={0} />
        <Tab label="وارد کردن اطلاعات بار" value={1} />
        <Tab label="تحویلی کشتارگاه" value={2} />
        <Tab label="بارهای حذف شده" value={3} />
        <Tab label="فروش به خارج استان" value={4} />
        <Tab label="بارهای زنجیره" value={5} />
        <Tab label="خرید خارج از استان" value={6} />
        <Tab label="عدم وصول" value={7} />
        {getRoleFromUrl() === "Supporter" ||
          (getRoleFromUrl() === "AdminX" && (
            <Tab label="تسویه حساب" value={8} />
          ))}
      </Tabs>
    );
  } else if (getRoleFromUrl() === "LiveStockSupport") {
    tabs = null;
  } else {
    tabs = (
      <Tabs
        scrollButtons="auto"
        variant="scrollable"
        allowScrollButtonsMobile
        value={selectedTab}
        onChange={handleTabChange}
      >
        <Tab label="کشتار داخل استان" value={0} />
        <Tab label="بارهای حذف شده" value={3} />
        {(getRoleFromUrl() === "VetFarm" ||
          getRoleFromUrl() === "VetSupervisor" ||
          getRoleFromUrl() === "ProvinceSupervisor") && (
          <Tab label="فروش به خارج استان" value={4} />
        )}

        {(getRoleFromUrl() === "VetFarm" ||
          getRoleFromUrl() === "VetSupervisor" ||
          getRoleFromUrl() === "ProvinceSupervisor") && (
          <Tab label="بارهای زنجیره" value={5} />
        )}

        {!getRoleFromUrl() === "VetFarm" && (
          <Tab label="خرید خارج از استان" value={6} />
        )}

        {getRoleFromUrl() !== "KillHouse" && <Tab label="عدم وصول" value={7} />}
      </Tabs>
    );
  }

  const aggregateValidationHasError = () => {
    return (
      aggregates?.reduce((total, obj) => total + obj?.quantity, 0) >
        aggregateStatus?.limitation ||
      !aggregates.every(
        (obj) =>
          obj.poultryRequest?.poultry?.unitName ===
            aggregates[0]?.poultryRequest?.poultry?.unitName &&
          obj.killhouseUser?.name === aggregates[0]?.killhouseUser?.name
      )
    );
  };

  return (
    <Grid
      container
      direction="column"
      flexWrap="nowrap"
      mt={SPACING.SMALL}
      xs={12}
    >
      <Grid container justifyContent="center" mb={SPACING.MEDIUM}>
        {tabs}
      </Grid>
      {selectedTab === 0 && (
        <Grid
          container
          alignItems="center"
          justifyContent="center"
          xs={12}
          mb={4}
          px={2}
        >
          {tableTitle}
          <Grid container mt={2} isDashboard xs={12}>
            <ResponsiveTable
              title={"خلاصه اطلاعات"}
              noPagination
              isDashboard
              columns={[
                "تعداد بار",
                "حجم بار",
                "وزن بار",
                "حجم دولتی",
                "وزن دولتی",
                "حجم آزاد",
                "وزن آزاد",
                "میانگین وزن",
                "کمترین سن ",
                "بیشترین سن ",
                "میانگین سنی",
                "بارهای دارای کد قرنطینه",
                "بارهای فاقد کد قرنطینه",
                "حجم بارهای فاقد کد قرنطینه",
                "بارهای دارای اختلاف",
                "حجم اختلاف بارها",
                "بارهای تحویلی کشتارگاه",
                "حجم نهایی در کشتارگاه	",
                "وزن نهایی در کشتارگاه",
                "تعداد بار ورودی به انبار",
                "حجم بار ورودی به انبار",
                "وزن لاشه",
                "درصد افت بار",
              ]}
              data={[
                [
                  <Typography
                    variant="caption"
                    key={"1"}
                    style={{ color: "blue" }}
                  >
                    {vetFarmBarsOverview?.lenKillRequest
                      ? vetFarmBarsOverview.lenKillRequest.toLocaleString()
                      : "0"}
                  </Typography>,
                  <Typography variant="caption" key={"1"}>
                    {vetFarmBarsOverview?.killRequestQuantity
                      ? vetFarmBarsOverview.killRequestQuantity.toLocaleString()
                      : "0"}
                  </Typography>,
                  <Typography
                    variant="caption"
                    key={"1"}
                    style={{ color: "blue" }}
                  >
                    {vetFarmBarsOverview?.killRequestWeight
                      ? vetFarmBarsOverview.killRequestWeight.toLocaleString()
                      : "0"}
                  </Typography>,
                  <Typography variant="caption" key={"1"}>
                    {vetFarmBarsOverview?.allGovernmentalQuantity
                      ? vetFarmBarsOverview.allGovernmentalQuantity.toLocaleString()
                      : "0"}
                  </Typography>,
                  <Typography variant="caption" key={"1"}>
                    {vetFarmBarsOverview?.allGovernmentalWeight
                      ? vetFarmBarsOverview.allGovernmentalWeight.toLocaleString()
                      : "0"}
                  </Typography>,
                  <Typography variant="caption" key={"1"}>
                    {vetFarmBarsOverview?.allFreeQuantity
                      ? vetFarmBarsOverview.allFreeQuantity.toLocaleString()
                      : "0"}
                  </Typography>,
                  <Typography variant="caption" key={"1"}>
                    {vetFarmBarsOverview?.allFreeWeight
                      ? vetFarmBarsOverview.allFreeWeight.toLocaleString()
                      : "0"}
                  </Typography>,
                  <Typography variant="caption" key={"1"}>
                    {vetFarmBarsOverview?.avgWeight || "0"}
                  </Typography>,
                  <Typography
                    variant="caption"
                    key={"1"}
                    style={{ color: "blue" }}
                  >
                    {vetFarmBarsOverview?.minAge || "0"}
                  </Typography>,
                  <Typography variant="caption" key={"1"}>
                    {vetFarmBarsOverview?.maxAge || "0"}
                  </Typography>,
                  <Typography
                    variant="caption"
                    key={"1"}
                    style={{ color: "blue" }}
                  >
                    {vetFarmBarsOverview?.avgAge || "0"}
                  </Typography>,
                  <Typography variant="caption" key={"1"}>
                    {vetFarmBarsOverview?.lenKillRequestHasCode
                      ? vetFarmBarsOverview.lenKillRequestHasCode.toLocaleString()
                      : "0"}
                  </Typography>,

                  <Typography variant="caption" key={"1"}>
                    {vetFarmBarsOverview?.lenKillRequestHasNotCode
                      ? vetFarmBarsOverview.lenKillRequestHasNotCode.toLocaleString()
                      : "0"}
                  </Typography>,
                  <Typography
                    variant="caption"
                    key={"1"}
                    style={{ color: "blue" }}
                  >
                    {vetFarmBarsOverview?.quantityOfKillRequestHasNotCode
                      ? vetFarmBarsOverview.quantityOfKillRequestHasNotCode.toLocaleString()
                      : "0"}
                  </Typography>,
                  <Typography variant="caption" key={"1"}>
                    {vetFarmBarsOverview?.differenceBar
                      ? vetFarmBarsOverview.differenceBar.toLocaleString()
                      : "0"}
                  </Typography>,
                  <Typography variant="caption" key={"1"}>
                    {vetFarmBarsOverview?.finalRealQuantity
                      ? vetFarmBarsOverview.finalRealQuantity.toLocaleString()
                      : "0"}
                  </Typography>,
                  <Typography
                    variant="caption"
                    key={"1"}
                    style={{ color: "blue" }}
                  >
                    {vetFarmBarsOverview?.lenCompleteWithKillHouse
                      ? vetFarmBarsOverview.lenCompleteWithKillHouse.toLocaleString()
                      : "0"}
                  </Typography>,
                  <Typography variant="caption" key={"1"}>
                    {vetFarmBarsOverview?.quantityFinalKillHouse
                      ? vetFarmBarsOverview.quantityFinalKillHouse.toLocaleString()
                      : "0"}
                  </Typography>,
                  <Typography
                    variant="caption"
                    key={"1"}
                    style={{ color: "blue" }}
                  >
                    {vetFarmBarsOverview?.weightFinalKillHouse
                      ? vetFarmBarsOverview.weightFinalKillHouse.toLocaleString()
                      : "0"}
                  </Typography>,
                  <Typography variant="caption" key={"1"}>
                    {vetFarmBarsOverview?.wareHouseBars
                      ? vetFarmBarsOverview.wareHouseBars.toLocaleString()
                      : "0"}
                  </Typography>,
                  <Typography
                    variant="caption"
                    key={"1"}
                    style={{ color: "blue" }}
                  >
                    {vetFarmBarsOverview?.wareHouseBarsQuantity
                      ? vetFarmBarsOverview.wareHouseBarsQuantity.toLocaleString()
                      : "0"}
                  </Typography>,
                  <Typography variant="caption" key={"1"}>
                    {vetFarmBarsOverview?.wareHouseBarsWeight
                      ? vetFarmBarsOverview.wareHouseBarsWeight.toLocaleString()
                      : "0"}
                  </Typography>,
                  <Typography
                    variant="caption"
                    key={"1"}
                    style={{ color: "blue" }}
                  >
                    {vetFarmBarsOverview?.wareHouseBarsWeightLose
                      ? vetFarmBarsOverview.wareHouseBarsWeightLose
                          .toFixed(2)
                          .toLocaleString()
                      : "0"}
                  </Typography>,
                ],
              ]}
            />
          </Grid>

          {aggregateStatus?.allow &&
            (getRoleFromUrl() === "VetFarm" ||
              getRoleFromUrl() === "AdminX" ||
              getRoleFromUrl() === "SuperAdmin") && (
              <Grid id="merge" container xs={12} justifyContent="end">
                <Button
                  color={aggregateValidationHasError() ? "error" : "primary"}
                  variant="outlined"
                  disabled={
                    aggregates.some((item) => item?.clearanceCode)
                      ? true
                      : aggregates.some((item) => item?.aggregateCode)
                      ? false
                      : aggregates?.length < 2
                  }
                  onClick={() => {
                    if (aggregateValidationHasError()) {
                      openNotif({
                        vertical: "top",
                        horizontal: "center",
                        msg: `فقط بارهای با خریدار و مرغدار یکسان و با مجموع تعداد حداکثر ${aggregateStatus?.limitation} میتوانید ادغام کنید!`,
                        severity: "error",
                      });
                    } else {
                      dispatch(
                        OPEN_MODAL({
                          title:
                            aggregates.some((item) => item?.aggregateCode) &&
                            !aggregates.some((item) => item?.clearanceCode)
                              ? "ورود اطلاعات / لغو ادغام"
                              : "ادغام بارها",
                          content: (
                            <VetFarmAggregateBars
                              setAggregates={setAggregates}
                              bars={
                                aggregates.some((item) => item?.aggregateCode)
                                  ? data?.filter(
                                      (item) =>
                                        item?.aggregateCode ===
                                        aggregates[0]?.aggregateCode
                                    )
                                  : aggregates
                              }
                              updateTable={updateTable}
                              canReturn={
                                aggregates.some(
                                  (item) => item?.aggregateCode
                                ) &&
                                !aggregates.some((item) => item?.clearanceCode)
                              }
                            />
                          ),
                        })
                      );
                    }
                  }}
                >
                  {aggregates.some((item) => item?.aggregateCode) &&
                  !aggregates.some((item) => item?.clearanceCode)
                    ? "ورود اطلاعات / لغو ادغام"
                    : "ادغام بارها"}
                </Button>
              </Grid>
            )}

          <ResponsiveTable
            data={tableData}
            columns={[
              "ردیف",
              "ادغام",
              "وضعیت",
              "کدبار",
              "تاریخ ثبت خودرو",
              "کشتار",
              "فروش",
              "خریدار",
              "کشتارکن اختصاصی",
              "مشخصات مرغدار",
              "نام فارم",
              "تعداد اولیه",
              "وزن اولیه بار (کیلوگرم)",
              "کد بهداشتی حمل و نقل",
              "قیمت مرغ زنده‌ی بار",
              "کدرهگیری سامانه قرنطینه",
              "تعداد در قرنطینه",
              // "ماشین واقعی حمل",
              "ماشین",
              "راننده",
              "نژاد",
              "سن",
              "میانگین وزن اولیه (کیلوگرم)",
              ...(getRoleFromUrl() === "VetFarm"
                ? []
                : ["قیمت مرغدار", "قیمت کشتارگاه", "قیمت تعاونی"]),
              "دامپزشک فارم",
              "محل کشتار",
              "شهر",
              "تاریخ کشتار",
              "کدسفارش کشتار",
              ...(getRoleFromUrl() === "VetFarm"
                ? []
                : [
                    "وضعیت سند",
                    "سند (بارنامه)",
                    "تعداد نهایی",
                    "وزن نهایی بار (کیلوگرم)",
                    "میانگین وزن نهایی (کیلوگرم)",
                    "حجم لاشه",
                    "وزن لاشه",
                    "درصد افت",
                  ]),
              ...information(),
              "عملیات",
            ]}
            handlePageChange={handlePageChange}
            totalRows={totalRows}
            page={page}
            perPage={perPage}
            handlePerRowsChange={handlePerRowsChange}
            title="مدیریت بارها"
          />
        </Grid>
      )}

      {selectedTab === 1 && <EnterAggregateLoadInformation />}
      {selectedTab === 2 && <SlaughterManageBars />}

      {selectedTab === 3 && (
        <Grid mt={SPACING.MEDIUM}>
          <VetFarmDeletedBars />
        </Grid>
      )}

      {(getRoleFromUrl() === "ProvinceOperator" ||
        getRoleFromUrl() === "CityOperator" ||
        getRoleFromUrl() === "SuperAdmin" ||
        getRoleFromUrl() === "VetFarm" ||
        getRoleFromUrl() === "VetSupervisor" ||
        getRoleFromUrl() === "AdminX" ||
        getRoleFromUrl() === "Supporter" ||
        getRoleFromUrl() === "ProvinceSupervisor") && (
        <>
          {selectedTab === 4 && (
            <Grid mt={SPACING.MEDIUM}>
              <VetFarmOutOfProvince
                readOnly={
                  getRoleFromUrl() === "VetSupervisor" ||
                  getRoleFromUrl() === "CityOperator" ||
                  getRoleFromUrl() === "ProvinceSupervisor"
                }
              />
            </Grid>
          )}
        </>
      )}

      {selectedTab === 5 && <ChainBarManagement />}
      {selectedTab === 6 && <SlaughterOutProvinceBars />}
      {selectedTab === 7 && <SlaughterEnterNoneReciept />}
      {selectedTab === 8 && <SupporterSettlement />}
    </Grid>
  );
};

// const DisabledWrap = ({ children, checked }) => {
//   return <Grid style={{ opacity: !checked ? 0.5 : 1 }}>{children}</Grid>;
// };
