import { endOfMonth, format, startOfMonth } from "date-fns";
import styles from "./App.module.scss";
import Calendar from "./calendar/Calendar";
import { useEffect } from "react";

export default function App() {
  const onDateClick = async (date: Date) => {
    const start = startOfMonth(date);
    const end = endOfMonth(date);

    const fmt = (date: Date) => format(date, "YMMdd");
    const fmtDate = fmt(date);
    const fmtStart = fmt(start);
    const fmtEnd = fmt(end);
    console.log(fmtStart, fmtDate, fmtEnd);

    const journals: any[] = await logseq.DB.datascriptQuery(`
      [:find (pull ?p [*])
      :where
      [?b :block/page ?p]
      [?p :block/journal? true]
      [?p :block/journal-day ?d]
      [(>= ?d ${fmtStart})] [(<= ?d ${fmtEnd})]]
    `);
    const journalsMap = new Map(
      journals.flatMap((x) => x).map((x) => [x["journal-day"].toString(), x])
    );
    console.log("JOURNALS", journalsMap);

    const targetEntry = journalsMap.get(fmtDate);
    console.log("Target", targetEntry);

    let name;
    if (targetEntry) name = targetEntry["original-name"];
    else {
      // TODO: Try to create a new journal page?
      return;
    }

    logseq.App.pushState("page", { name });
    logseq.hideMainUI();
  };

  return (
    <main className={styles.app}>
      <div className="header">
        Header
        <button onClick={() => logseq.hideMainUI()}>Close</button>
      </div>

      <Calendar onDateClick={onDateClick} />
    </main>
  );
}
