import { Switch } from "@mui/material";
import { useState } from "react";
import { useDispatch } from "react-redux";
import { Grid } from "../../../../components/grid/Grid";
import { SPACING } from "../../../../data/spacing";
import { manageProcessBuyReqService } from "../../services/manage-process-buy-req";
import { manageProcessBuyReqOperationService } from "../../services/manage-process-buy-req-operation";

export const ProvinceManageBuyReqAllowOperation = ({
  item,
  getLimitInformation,
  isDebt,
}) => {
  const dispatch = useDispatch();
  const [isChecked, setIsChecked] = useState(
    isDebt
      ? item.allowPurchaseRequest.totalLimitation
      : item.allowPurchaseRequest.allow
  );

  const handleSwitchChange = () => {
    if (isDebt) {
      setIsChecked(!isChecked);
      dispatch(
        manageProcessBuyReqOperationService({
          kill_house_key: item.key,
          total_limitation: !isChecked,
        })
      ).then((r) => {
        dispatch(manageProcessBuyReqService());
        getLimitInformation();
      });
    } else {
      setIsChecked(!isChecked);
      dispatch(
        manageProcessBuyReqOperationService({
          kill_house_key: item.key,
          allow: !isChecked,
        })
      ).then((r) => {
        dispatch(manageProcessBuyReqService());
        getLimitInformation();
      });
    }
  };

  return (
    <Grid
      container
      alignItems="center"
      justifyContent="center"
      gap={SPACING.SMALL}
    >
      <Grid container alignItems="center">
        <Switch
          checked={isChecked} // Connect the switch to the state
          onChange={handleSwitchChange} // Update the state when the switch is toggled
          color="primary" // Optional: Set the switch color
        />
        {/* {!isDebt && <span>{isChecked ? "دارد" : "ندارد"}</span>} */}
      </Grid>
    </Grid>
  );
};
