import { Checkbox, FormControlLabel, IconButton, Tooltip } from "@mui/material";
import { useEffect, useState } from "react";
import { useDispatch } from "react-redux";
import { Grid } from "../../../../components/grid/Grid";
import { SPACING } from "../../../../data/spacing";
import { getDirectBuyPermissionService } from "../../services/get-direct-buy-permission";
import { postDirectBuyPermissionService } from "../../services/post-direct-buy-permission";
// import { updateLossesPermissionService } from "../../services/update-losses-permission";
import TuneIcon from "@mui/icons-material/Tune";
import { useNavigate } from "react-router-dom";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import {
  ROUTE_ADMINX_ROUTE_POLICY_COUNCIL_DIRECT_BUY,
  ROUTE_PROVINCE_ROUTE_POLICY_COUNCIL_DIRECT_BUY,
  ROUTE_SUPER_ADMIN_ROUTE_POLICY_COUNCIL_DIRECT_BUY,
} from "../../../../routes/routes";

export const ProvinceSlaughterDirectBuyPermission = () => {
  const navigate = useNavigate();
  const [isChecked, setIsChecked] = useState(false);
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(getDirectBuyPermissionService()).then((r) => {
      setIsChecked(r.payload.data.allowState);
    });
  }, []);

  // useEffect(() => {
  //   if (!isChecked) {
  //     dispatch(
  //       postDirectBuyPermissionService({
  //         allow: false,
  //       })
  //     );
  //   } else
  // }, [isChecked]);

  const handleChange = (event) => {
    dispatch(
      postDirectBuyPermissionService({
        allow: event.target.checked,
      })
    );
    setIsChecked(event.target.checked);
  };

  return (
    <Grid container alignItems="center" gap={SPACING.TINY}>
      <FormControlLabel
        control={
          <Checkbox checked={isChecked} onChange={handleChange} name="item4" />
        }
        label="دسترسی کشتارگاه/کشتارکن برای ثبت خرید مستقیم"
      />
      <Tooltip title="مدیریت">
        <IconButton
          disabled={!isChecked}
          color="success"
          onClick={() => {
            navigate(
              `${
                getRoleFromUrl() === "AdminX"
                  ? ROUTE_ADMINX_ROUTE_POLICY_COUNCIL_DIRECT_BUY
                  : getRoleFromUrl() === "SuperAdmin"
                  ? ROUTE_SUPER_ADMIN_ROUTE_POLICY_COUNCIL_DIRECT_BUY
                  : getRoleFromUrl() === "ProvinceFinancial"
                  ? ROUTE_PROVINCE_ROUTE_POLICY_COUNCIL_DIRECT_BUY
                  : ""
              }`
            );
          }}
        >
          <TuneIcon />
        </IconButton>
      </Tooltip>
    </Grid>
  );
};
