import { Autocomplete, Button, TextField } from "@mui/material";
import { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { Grid } from "../../../../components/grid/Grid";
import { CLOSE_MODAL } from "../../../../lib/redux/slices/appSlice";
import { getCitiesService } from "../../services/get-cities";
import { provinceEditPoultryCityService } from "../../services/province-edit-poultry-city";

export const EditPoultryCity = ({ item, updateTable }) => {
  const dispatch = useDispatch();
  const [sellected, setSellected] = useState();
  const { getCitiesOptions } = useSelector((state) => state.provinceSlice);
  const getOptionLabel = (option) => option.label; // Customize how the label is displayed

  useEffect(() => {
    dispatch(getCitiesService());
  }, []);

  return (
    <Grid container gap={1} width="100%">
      <Autocomplete
        options={getCitiesOptions}
        getOptionLabel={getOptionLabel}
        sx={{ width: "100%" }}
        onChange={(event, value) => setSellected(value)}
        value={sellected}
        renderInput={(params) => <TextField {...params} label="تعاونی" />}
      />
      <Button
        fullWidth
        variant="contained"
        onClick={() => {
          if (sellected) {
            dispatch(
              provinceEditPoultryCityService({
                key: item.key,
                city_operator: sellected.value,
              })
            ).then((r) => {
              dispatch(CLOSE_MODAL());
              updateTable();
            });
          }
        }}
      >
        ثبت
      </Button>
    </Grid>
  );
};
