import { MenuItem, Select } from "@mui/material";
import { useContext, useState } from "react";
import { useDispatch } from "react-redux";
import { AppContext } from "../../../../contexts/AppContext";
import { slaughterGetKillerKillhousesService } from "../../../slaughter-house/services/slaughter-get-killers-killhouses";
import { provinceGetSlaughterhousesQuotaService } from "../../services/province-get-slaughterhouses-quota";
import { provinceUpdateKillerIdentityService } from "../../services/province-update-killer-identity";

export const ProvinceUpdateKillerIdentity = ({
  slaughterKey,
  disableSelect,
  killerType,
}) => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);
  const [selectedOption, setSelectedOption] = useState(killerType);
  const handleOptionChange = (event) => {
    dispatch(
      provinceUpdateKillerIdentityService({
        kill_house_key: slaughterKey,
        type: event.target.value,
      })
    ).then((r) => {
      if (r.payload.error) {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: r.payload.error,
          severity: "error",
        });
      } else {
        setSelectedOption(event.target.value);
        dispatch(provinceGetSlaughterhousesQuotaService());
        dispatch(slaughterGetKillerKillhousesService());
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: "عملیات با موفقیت انجام شد.",
          severity: "success",
        });
      }
    });
  };

  return (
    <>
      {disableSelect ? (
        "-"
      ) : (
        <Select
          disabled={disableSelect}
          label="Select Option"
          value={selectedOption}
          onChange={handleOptionChange}
          style={{ width: 140 }}
          size="small"
        >
          <MenuItem value="public">عمومی</MenuItem>
          <MenuItem value="exclusive">اختصاصی</MenuItem>
        </Select>
      )}
    </>
  );
};
