import { useEffect } from "react";
import { useSearchParams } from "react-router-dom";
import { MemoRenderContext } from "@/components/MasonryView";
import MemoView from "@/components/MemoView";
import PagedMemoList from "@/components/PagedMemoList";
import { useMemoFilterContext } from "@/contexts/MemoFilterContext";
import { useMemoFilters, useMemoSorting } from "@/hooks";
import useCurrentUser from "@/hooks/useCurrentUser";
import { State } from "@/types/proto/api/v1/common_pb";
import { Memo } from "@/types/proto/api/v1/memo_service_pb";

const Home = () => {
  const user = useCurrentUser();
  const [searchParams] = useSearchParams();
  const { addFilter } = useMemoFilterContext();

  // Auto-set today's date filter if no filter is present
  useEffect(() => {
    // Check if there's already a filter in URL
    const hasFilterInUrl = searchParams.has("filter");

    // Only set default date filter if no filter exists in URL
    if (!hasFilterInUrl) {
      // Get today's date in YYYY-MM-DD format (UTC)
      const today = new Date();
      const year = today.getUTCFullYear();
      const month = String(today.getUTCMonth() + 1).padStart(2, "0");
      const day = String(today.getUTCDate()).padStart(2, "0");
      const todayStr = `${year}-${month}-${day}`;

      // Add displayTime filter for today
      addFilter({ factor: "displayTime", value: todayStr });
    }
  }, [searchParams, addFilter]);

  // Build filter using unified hook
  const memoFilter = useMemoFilters({
    creatorName: user?.name,
    includeShortcuts: true,
    includePinned: true,
  });

  // Get sorting logic using unified hook
  const { listSort, orderBy } = useMemoSorting({
    pinnedFirst: true,
    state: State.NORMAL,
  });

  return (
    <div className="w-full min-h-full bg-background text-foreground">
      {/* Regular Memos List - Bookmarks are now in sidebar */}
      <PagedMemoList
        renderer={(memo: Memo, context?: MemoRenderContext) => (
          <MemoView key={`${memo.name}-${memo.displayTime}`} memo={memo} showVisibility showPinned compact={context?.compact} />
        )}
        listSort={listSort}
        orderBy={orderBy}
        filter={memoFilter}
      />
    </div>
  );
};

export default Home;

