"use client";

import NotesView from "@/app/[language]/note/components/NotesView";
import PositionInput from "@/app/[language]/note/components/PositionInput";
import WantInput from "@/app/[language]/note/components/WantInput";
import useGetNote from "@/app/[language]/note/query/useGetNote";

import { useNoteStore } from "@/state/Stores";
import { formatText } from "@/utilities/Utility";
import { observer } from "mobx-react-lite";
import { useTranslations } from "next-intl";
import { useParams } from "next/navigation";
import { useEffect, useMemo } from "react";
import Stack from "react-bootstrap/Stack";
import { useIntParam } from "taehui-lib/fe-utilities";

export default observer(() => {
  const {
    setLastSrc,
    setWantAvatar,
    setLastPage,
    lastWant,
    lastSrc,
    setWantInput,
    setLastWant,
  } = useNoteStore();
  const t = useTranslations();

  let { want: [want] = [""] } = useParams<{ want: string[] }>();
  want = useMemo(() => decodeURIComponent(want), [want]);
  const { param: src } = useIntParam("src", 0);
  const { param: page, setParam: setPage } = useIntParam("page", 1);

  const {
    data: { topCount, totalCount, lastPage },
    isFetched: isNoteLoaded,
  } = useGetNote();

  useEffect(() => {
    if ((want !== lastWant || src !== lastSrc) && page > 1) {
      setPage(1);
    }
  }, [lastSrc, lastWant, page, setPage, src, want]);

  useEffect(() => {
    if (isNoteLoaded) {
      setLastPage(lastPage);
    }
  }, [isNoteLoaded, lastPage, setLastPage]);

  useEffect(() => {
    setWantInput(want);
  }, [setWantInput, want]);

  useEffect(() => {
    setLastWant(want);
  }, [setLastWant, want]);

  useEffect(() => {
    setLastSrc(src);
  }, [setLastSrc, src]);

  useEffect(() => {
    setWantAvatar(src === 1 ? want : "");
  }, [setWantAvatar, src, want]);

  return (
    <Stack gap={2}>
      <WantInput />
      <hr />
      <NotesView />
      <PositionInput />
      <hr />
      {isNoteLoaded && (
        <>
          {t("topCountText", {
            topCount: formatText(topCount),
          })}
          <br />
          {t("totalCountText", { totalCount: formatText(totalCount) })}
        </>
      )}
      <span
        dangerouslySetInnerHTML={{
          __html: t.raw("bannedNoteFile"),
        }}
      />
    </Stack>
  );
});
