import { useEffect } from "react";
import { useImmer } from "use-immer";

type messageInfo = {
  severity: "success" | "error" | "warning" | "info";
  content: string;
};

const useMySnackbar = () => {
  const [snackPack, setSnackPack] = useImmer<Array<messageInfo>>([]);
  const [open, setOpen] = useImmer<boolean>(false);
  const [messageInfo, setMessageInfo] = useImmer<messageInfo>({
    severity: "success",
    content: "",
  });

  const success = (content: string) => {
    setSnackPack((draft: Array<messageInfo>) => {
      draft.push({ severity: "success", content });
    });
  };

  const error = (content: string) => {
    setSnackPack((draft: Array<messageInfo>) => {
      draft.push({ severity: "error", content });
    });
  };

  const warning = (content: string) => {
    setSnackPack((draft: Array<messageInfo>) => {
      draft.push({ severity: "warning", content });
    });
  };

  const info = (content: string) => {
    setSnackPack((draft: Array<messageInfo>) => {
      draft.push({ severity: "info", content });
    });
  };

  const close = (event: React.SyntheticEvent<any> | Event, reason: string) => {
    if (reason === "clickaway") {
      return;
    }
    setOpen(false);
  };

  useEffect(() => {
    if (snackPack.length && !messageInfo.content) {
      setMessageInfo({ ...snackPack[0] });
      setSnackPack((draft: Array<messageInfo>) => {
        draft.splice(0, 1);
      });
      setOpen(true);
    } else if (snackPack.length && messageInfo.content && open) {
      setOpen(false);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [snackPack, messageInfo.content, open]);

  const handleExited = () => {
    setMessageInfo((prev) => {
      return {
        severity: prev.severity,
        content: "",
      };
    });
  };

  return {
    open,
    messageInfo,
    handleExited,
    success,
    error,
    warning,
    info,
    close,
  };
};

export default useMySnackbar;
