import { MenuItem, Select } from "@mui/material";
import { useContext, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { Grid } from "../../../../components/grid/Grid";
import { AppContext } from "../../../../contexts/AppContext";
import { slaughterGetKillerKillhousesService } from "../../../slaughter-house/services/slaughter-get-killers-killhouses";
import { provinceGetSlaughterhousesQuotaService } from "../../services/province-get-slaughterhouses-quota";
import { provinceUpdateSlaughterKillplaceService } from "../../services/province-update-slaughter-killplace";

export const ProvinceSelectSlaughterForSlaughter = ({
  // onSlaughterChange,
  killHouseForKiller,
  slaughterKey,
  disabled,
}) => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);
  const [selectedValue, setSelectedValue] = useState(killHouseForKiller?.key);
  const { slaughterGetKillerKillhouses } = useSelector(
    (state) => state.slaughterSlice
  );

  // useEffect(() => {
  //   setSelectedValue(killHouseForKiller?.key);
  // }, []);

  const handleChange = (event) => {
    dispatch(
      provinceUpdateSlaughterKillplaceService({
        percentage_key: slaughterKey,
        kill_house_key: event.target.value,
      })
    ).then((r) => {
      if (r.payload.error) {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: r.payload.error,
          severity: "error",
        });
      } else {
        dispatch(provinceGetSlaughterhousesQuotaService());
        dispatch(slaughterGetKillerKillhousesService());
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: "عملیات با موفقیت انجام شد.",
          severity: "success",
        });
      }
    });
    setSelectedValue(event.target.value);
  };

  return (
    <Grid container alignItems="center" justifyContent="center">
      <Select
        labelId="demo-simple-select-label"
        id="demo-simple-select"
        value={selectedValue}
        onChange={handleChange}
        style={{ width: "170px" }}
        size="small"
        disabled={disabled}
      >
        {slaughterGetKillerKillhouses?.map((item, i) => {
          return (
            <MenuItem key={i} value={item.key}>
              {item.name}
            </MenuItem>
          );
        })}
      </Select>
    </Grid>
  );
};
