import React, { useContext, useState } from "react";
import { Grid } from "../../../../components/grid/Grid";
import { Autocomplete, Button, TextField } from "@mui/material";
import { useDispatch } from "react-redux";
import { provincePoultryScienceExpertsEditPoultryService } from "../../services/province-poultry-science-experts-add-poultry-service";
import { AppContext } from "../../../../contexts/AppContext";
import { CLOSE_MODAL } from "../../../../lib/redux/slices/appSlice";

export const ProvincePoultryScienceExpertsAddPoultry = ({
  item,
  updateTable,
  poultryExperts,
}) => {
  const [poultryId, setPoultryId] = useState();
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);

  const poultryExpertOptions = poultryExperts
    ? poultryExperts.map((i) => ({
        id: i.id,
        label: `${i.unitName || "-"} (${i.user?.fullname || "-"} - ${
          i.user?.mobile || "-"
        })`,
      }))
    : [];

  const poultryItemOptions = item?.poultry
    ? item.poultry.map((poultry) => ({
        id: poultry.id,
        label: `${poultry.unitName || "-"} (${
          poultry.user?.fullname || "-"
        } - ${poultry.user?.mobile || "-"})`,
      }))
    : [];

  const allOptions = [
    ...poultryItemOptions,
    ...poultryExpertOptions.filter(
      (expert) => !poultryItemOptions.some((item) => item.id === expert.id)
    ),
  ];

  const defaultSelectedItems = poultryItemOptions;

  const handleSubmit = () => {
    dispatch(
      provincePoultryScienceExpertsEditPoultryService({
        poultry: poultryId,
        poultry_science_id: item.id,
      })
    ).then((r) => {
      if (r.payload.error) {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: r.payload.error,
          severity: "error",
        });
      } else {
        updateTable();
        dispatch(CLOSE_MODAL());
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: "عملیات با موفقیت انجام شد.",
          severity: "success",
        });
      }
    });
  };

  return (
    <Grid container xs={12} justifyContent="center" direction="column" gap={2}>
      <Grid>
        <Autocomplete
          disablePortal
          multiple
          defaultValue={defaultSelectedItems}
          id="province"
          options={allOptions}
          getOptionLabel={(option) => option.label}
          isOptionEqualToValue={(option, value) => option.id === value.id}
          onChange={(e, value) => {
            setPoultryId(value.map((opt) => opt.id));
          }}
          renderInput={(params) => (
            <TextField {...params} label="مرغداری را انتخاب  کنید" />
          )}
        />
      </Grid>
      <Button fullWidth variant="contained" onClick={handleSubmit}>
        ثبت
      </Button>
    </Grid>
  );
};
