import { IonBackButton, IonButtons, IonTitle, IonToolbar } from "@ionic/react";
import { NotificationView } from "threadiverse";

import { FetchFn } from "#/features/feed/Feed";
import InboxFeed from "#/features/feed/InboxFeed";
import { receivedInboxItems } from "#/features/inbox/inboxSlice";
import AppHeader from "#/features/shared/AppHeader";
import { AppPage } from "#/helpers/AppPage";
import useClient from "#/helpers/useClient";
import FeedContent from "#/routes/pages/shared/FeedContent";
import { useAppDispatch } from "#/store";

import MarkAllAsReadButton from "./MarkAllAsReadButton";

interface RepliesPageProps {
  type: "Comment" | "Post";
}

export default function RepliesPage({ type }: RepliesPageProps) {
  const dispatch = useAppDispatch();
  const client = useClient();

  const fetchFn: FetchFn<NotificationView> = async (page_cursor, ...rest) => {
    // TODO - actually paginate properly if Lemmy implements
    // reply pagination filtering by comment and post
    const response = await client.getNotifications(
      {
        type_: "reply",
        page_cursor,
        limit: 50,
        unread_only: false,
      },
      ...rest,
    );

    const data = response.data.filter((reply) =>
      type === "Post" ? isPostReply(reply) : !isPostReply(reply),
    );

    dispatch(receivedInboxItems(data));

    return { ...response, data };
  };

  return (
    <AppPage>
      <AppHeader>
        <IonToolbar>
          <IonButtons slot="start">
            <IonBackButton defaultHref="/inbox" text="Boxes" />
          </IonButtons>

          <IonTitle>{type} Replies</IonTitle>

          <IonButtons slot="end">
            <MarkAllAsReadButton />
          </IonButtons>
        </IonToolbar>
      </AppHeader>
      <FeedContent>
        <InboxFeed fetchFn={fetchFn} />
      </FeedContent>
    </AppPage>
  );
}

export function isPostReply(reply: NotificationView): boolean {
  if (reply.data.type_ !== "comment") return false;
  // path = 0.xxxxx is a reply to a post
  return reply.data.comment.path.split(".").length === 2;
}
