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, getFiltersByFactor } = useMemoFilterContext();

  // Auto-set today's date filter if no filter is present
  useEffect(() => {
    if (!user) return;
    
    // 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 });
    }
  }, [user, 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,
  });

  if (!user) {
    return (
      <div className="w-full min-h-full flex flex-col justify-start items-center p-4">
        <div className="w-full max-w-3xl flex flex-col justify-start items-center">
          <div className="w-full h-32 bg-muted/20 animate-pulse rounded-xl mb-4" />
          <div className="w-full h-32 bg-muted/20 animate-pulse rounded-xl mb-4" />
          <div className="w-full h-32 bg-muted/20 animate-pulse rounded-xl mb-4" />
        </div>
      </div>
    );
  }

  return (
    <div className="w-full min-h-full bg-background text-foreground">
      <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;
