import { mailOutline, mailUnreadOutline } from "ionicons/icons";

import MoreActions from "#/features/comment/CommentEllipsis";
import { buildMarkRead } from "#/helpers/toastMessages";
import useAppToast from "#/helpers/useAppToast";
import { useAppDispatch, useAppSelector } from "#/store";

import { InboxItemView } from "./InboxItem";
import { getNotificationKey, markNotificationRead } from "./inboxSlice";
import MarkReadMoreActions from "./MarkReadMoreActions";
import PrivateMessageMoreActions from "./PrivateMessageMoreActions";

import styles from "./InboxItemMoreActions.module.css";

interface InboxItemMoreActionsProps {
  item: InboxItemView;

  ref: React.RefObject<InboxItemMoreActionsHandle | undefined>;
}

export interface InboxItemMoreActionsHandle {
  present: () => void;
}

export default function InboxItemMoreActions({
  item,
  ref,
}: InboxItemMoreActionsProps) {
  const dispatch = useAppDispatch();
  const readByInboxItemId = useAppSelector(
    (state) => state.inbox.readByInboxItemId,
  );
  const isRead = readByInboxItemId[getNotificationKey(item.notification)];
  const presentToast = useAppToast();

  const markReadAction = {
    text: isRead ? "Mark Unread" : "Mark Read",
    icon: isRead ? mailUnreadOutline : mailOutline,
    handler: () => {
      (async () => {
        const targetReadStatus = !isRead;

        try {
          await dispatch(
            markNotificationRead(
              {
                kind: item.notification.kind,
                notificationId: item.notification.id,
              },
              targetReadStatus,
            ),
          );
        } catch (error) {
          presentToast(buildMarkRead(targetReadStatus));
          throw error;
        }
      })();
    },
  };

  function renderInner() {
    if (item.data.type_ === "comment") {
      return (
        <MoreActions
          comment={item.data}
          rootIndex={undefined}
          appendActions={[markReadAction]}
          ref={ref}
        />
      );
    }
    if (item.data.type_ === "private_message") {
      return (
        <PrivateMessageMoreActions
          item={item.data}
          notification={item.notification}
          markReadAction={markReadAction}
          ref={ref}
        />
      );
    }
    if (item.data.type_ === "mod_action" || item.data.type_ === "post") {
      return <MarkReadMoreActions markReadAction={markReadAction} ref={ref} />;
    }
    return null;
  }

  return <button className={styles.button}>{renderInner()}</button>;
}
