import { useContext, useEffect, useState } from "react";
import { AppContext } from "../../../../contexts/AppContext";
import { useDispatch, useSelector } from "react-redux";
import { Autocomplete, Button, Chip, TextField } from "@mui/material";
import { Grid } from "../../../../components/grid/Grid";
import { SPACING } from "../../../../data/spacing";
import {
  slaughterAddDailyListService,
  slaughterGetGuildsService,
} from "../../services/slaughter-add-daily-list";
import { DRAWER } from "../../../../lib/redux/slices/appSlice";
import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith";

export const SlaughterAddDailyList = ({ updateTable }) => {
  const [openNotif] = useContext(AppContext);
  const dispatch = useDispatch();
  const [guildsData, setGuildsData] = useState([]);
  const [selectedItems, setSelectedItems] = useState([]);
  const selectedSubUser = useSelector(
    (state) => state.userSlice.selectedSubUser
  );

  useEffect(() => {
    const fetchGuilds = async () => {
      dispatch(
        slaughterGetGuildsService({
          role_key:
            checkPathStartsWith("slaughter") || checkPathStartsWith("steward")
              ? selectedSubUser?.key || ""
              : "",
        })
      ).then((r) => {
        setGuildsData(r.payload.data);
      });
    };

    fetchGuilds();
  }, [dispatch]);

  const handleSubmit = () => {
    dispatch(
      slaughterAddDailyListService({
        guild_key_list: selectedItems.map((item) => item.key),
      })
    ).then((r) => {
      if (r.payload.error) {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: "خطا در ثبت لیست",
          severity: "error",
        });
      } else {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: "لیست با موفقیت ثبت شد.",
          severity: "success",
        });
        dispatch(DRAWER({ right: false, bottom: false, content: null }));
        updateTable(1);
      }
    });
  };
  const handleDelete = (key) => {
    setSelectedItems((prev) => prev.filter((item) => item.key !== key));
  };

  return (
    <Grid container direction="column" gap={SPACING.SMALL}>
      <Autocomplete
        multiple
        disablePortal
        id="guilds-select"
        options={guildsData}
        renderTags={() => null}
        getOptionLabel={(option) =>
          `${option.steward ? "مباشر" : "صنف"} ${
            option.name || option.guildsName
          }
          ${option.user?.fullname || ""}
          (${option.user?.mobile || ""})`
        }
        onChange={(event, values) => {
          setSelectedItems(values);
        }}
        sx={{ width: "250px" }}
        renderInput={(params) => (
          <TextField
            {...params}
            fullWidth
            label="انتخاب مباشر / صنف"
            placeholder="انتخاب کنید"
          />
        )}
      />

      <Grid container direction="column" gap={1}>
        {selectedItems.map((item) => (
          <Chip
            key={item.key}
            label={`${item.steward ? "مباشر" : "صنف"} ${
              item.name || item.guildsName
            }`}
            onDelete={() => handleDelete(item.key)}
            sx={{ width: "fit-content" }}
          />
        ))}
      </Grid>

      <Button
        variant="contained"
        onClick={handleSubmit}
        disabled={selectedItems.length === 0}
      >
        ثبت
      </Button>
    </Grid>
  );
};
