/**
 * Copyright (c) 2023-present Pi Dash Software, Inc. and contributors
 * SPDX-License-Identifier: AGPL-3.0-only
 * See the LICENSE file for details.
 */

import { useCallback, useEffect, useMemo, useState } from "react";
import { observer } from "mobx-react";
// pi dash imports
import type { TDocumentInfo } from "@pi-dash/editor";
import { useTranslation } from "@pi-dash/i18n";
import { getReadTimeFromWordsCount } from "@pi-dash/utils";
// store
import type { TPageInstance } from "@/store/pages/base-page";

type Props = {
  page: TPageInstance;
};

const DEFAULT_DOCUMENT_INFO: TDocumentInfo = {
  words: 0,
  characters: 0,
  paragraphs: 0,
};

export const PageNavigationPaneInfoTabDocumentInfo = observer(function PageNavigationPaneInfoTabDocumentInfo(
  props: Props
) {
  const { page } = props;
  // states
  const [documentInfo, setDocumentInfo] = useState<TDocumentInfo>(DEFAULT_DOCUMENT_INFO);
  // derived values
  const {
    editor: { editorRef },
  } = page;
  // translation
  const { t } = useTranslation();
  // subscribe to asset changes
  useEffect(() => {
    const unsubscribe = editorRef?.onDocumentInfoChange(setDocumentInfo);
    // for initial render of this component to get the editor assets
    setDocumentInfo(editorRef?.getDocumentInfo() ?? DEFAULT_DOCUMENT_INFO);
    return () => {
      unsubscribe?.();
    };
  }, [editorRef]);

  const secondsToReadableTime = useCallback(() => {
    const wordsCount = documentInfo.words;
    const readTimeInSeconds = Number(getReadTimeFromWordsCount(wordsCount).toFixed(0));
    return readTimeInSeconds < 60 ? `${readTimeInSeconds}s` : `${Math.ceil(readTimeInSeconds / 60)}m`;
  }, [documentInfo.words]);

  const documentInfoCards = useMemo(
    () => [
      {
        key: "words-count",
        title: t("Words"),
        info: documentInfo.words,
      },
      {
        key: "characters-count",
        title: t("Characters"),
        info: documentInfo.characters,
      },
      {
        key: "paragraphs-count",
        title: t("Paragraphs"),
        info: documentInfo.paragraphs,
      },
      {
        key: "read-time",
        title: t("Read time"),
        info: secondsToReadableTime(),
      },
    ],
    [documentInfo, secondsToReadableTime, t]
  );

  return (
    <div className="grid grid-cols-2 gap-2">
      {documentInfoCards.map((card) => (
        <div key={card.key} className="rounded-sm bg-layer-2 p-2">
          <h6 className="text-14 font-semibold">{card.info}</h6>
          <p className="mt-1.5 text-13 font-medium text-tertiary">{card.title}</p>
        </div>
      ))}
    </div>
  );
});
