import React, { useEffect, useState } from "react";
import { Grid } from "../../../../components/grid/Grid";
import { SPACING } from "../../../../data/spacing";
import { Box, Tab, Tabs } from "@mui/material";
import { SlaughterSellCarcassOutProvinceBuyers } from "../slaughter-sell-carcass-out-province-buyers/SlaughterSellCarcassOutProvinceBuyers";
import { SlaughterSellCarcassOutProvinceSell } from "../slaughter-sell-carcass-out-province-sell/SlaughterSellCarcassOutProvinceSell";
import { useDispatch, useSelector } from "react-redux";
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 SlaughterSellCarcassOutProvincePage = () => {
  const dispatch = useDispatch();
  const selectedSubUser = useSelector(
    (state) => state.userSlice.selectedSubUser
  );
  const [valueOutProvince, setValueOutProvince] = useState(0);

  const handleChangeTabsetOutProvince = (event, newValue) => {
    setValueOutProvince(newValue);
  };

  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}
      width="100%"
    >
      <Grid container width="100%" isDashboard>
        <SlaughterShowProducts />
      </Grid>

      <Grid
        container
        direction="column"
        alignItems="center"
        justifyContent="space-between"
        gap={SPACING.SMALL}
        mb={SPACING.SMALL}
        width="100%"
      >
        <Box
          sx={{
            borderBottom: 1,
            borderColor: "divider",
          }}
        >
          <Tabs
            className="insidetabs"
            size="small"
            value={valueOutProvince}
            onChange={handleChangeTabsetOutProvince}
            aria-label="basic tabs example"
          >
            <Tab label="فروش" />
            <Tab label="خریداران" />
          </Tabs>
        </Box>

        {valueOutProvince === 0 && (
          <SlaughterSellCarcassOutProvinceSell fetchData={fetchData} />
        )}

        {valueOutProvince === 1 && <SlaughterSellCarcassOutProvinceBuyers />}
      </Grid>
    </Grid>
  );
};
