import { useMemo, useState } from "react";
import { Link } from "react-router-dom";
import { timestampDate } from "@bufbuild/protobuf/wkt";
import type { Memo } from "@/types/proto/api/v1/memo_service_pb";
import { useTranslate } from "@/utils/i18n";
import { cn } from "@/lib/utils";
import { BookmarkIcon, ChevronDownIcon, ChevronRightIcon, SparklesIcon } from "lucide-react";
import { useInfiniteMemos } from "@/hooks/useMemoQueries";
import { useMemoFilters } from "@/hooks";
import { State } from "@/types/proto/api/v1/common_pb";
import { DEFAULT_LIST_MEMOS_PAGE_SIZE } from "@/helpers/consts";
import i18n from "@/i18n";

interface PinnedSectionProps {
  creatorName?: string;
  className?: string;
}

// Number of days to consider a bookmark as "recent"
const RECENT_DAYS = 3;

const PinnedSection = ({ creatorName, className }: PinnedSectionProps) => {
  const t = useTranslate();
  const [showOlder, setShowOlder] = useState(false);

  // Build filter for pinned memos only
  const baseFilter = useMemoFilters({
    creatorName,
    includeShortcuts: true,
    includePinned: false, // Don't include pinned filter from context
  });

  // Add pinned filter
  const pinnedFilter = useMemo(() => {
    return baseFilter ? `${baseFilter} && pinned` : "pinned";
  }, [baseFilter]);

  // Fetch only pinned memos
  const { data: pinnedData, isLoading } = useInfiniteMemos({
    state: State.NORMAL,
    orderBy: "display_time desc",
    filter: pinnedFilter,
    pageSize: DEFAULT_LIST_MEMOS_PAGE_SIZE,
  });

  // Flatten pinned memos
  const pinnedMemos = useMemo(() => {
    return pinnedData?.pages.flatMap((page) => page.memos) || [];
  }, [pinnedData]);

  // Split memos into recent and older
  const { recentMemos, olderMemos } = useMemo(() => {
    const now = new Date();
    const recentThreshold = new Date(now.getTime() - RECENT_DAYS * 24 * 60 * 60 * 1000);

    const recent: Memo[] = [];
    const older: Memo[] = [];

    pinnedMemos.forEach((memo) => {
      if (!memo.displayTime) {
        older.push(memo);
        return;
      }
      const memoDate = timestampDate(memo.displayTime);
      if (memoDate && memoDate >= recentThreshold) {
        recent.push(memo);
      } else {
        older.push(memo);
      }
    });

    return { recentMemos: recent, olderMemos: older };
  }, [pinnedMemos]);

  if (isLoading || pinnedMemos.length === 0) {
    return null;
  }

  // Extract preview text (first line, max 50 chars)
  const getPreview = (content: string): string => {
    const firstLine = content.split("\n")[0].trim();
    // Remove markdown headers
    const cleanLine = firstLine.replace(/^#+\s*/, "");
    return cleanLine.length > 50 ? `${cleanLine.slice(0, 50)}...` : cleanLine;
  };

  // Format relative time
  const formatTime = (memo: Memo): string => {
    if (!memo.displayTime) return "";
    const date = timestampDate(memo.displayTime);
    if (!date) return "";

    const now = new Date();
    const diffMs = now.getTime() - date.getTime();
    const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
    const diffDays = Math.floor(diffHours / 24);

    if (diffHours < 1) return t("common.just-now" as any) || "Just now";
    if (diffHours < 24) return `${diffHours}h`;
    if (diffDays < 7) return `${diffDays}d`;
    return date.toLocaleDateString(i18n.language, { month: "short", day: "numeric" });
  };

  // Render a single bookmark card
  const renderBookmarkCard = (memo: Memo, isRecent: boolean = false) => {
    const preview = getPreview(memo.content || "");
    const timeStr = formatTime(memo);
    const memoPath = memo.name.startsWith("memos/") ? memo.name : `memos/${memo.name}`;

    return (
      <Link
        key={memo.name}
        to={`/${memoPath}`}
        className={cn(
          "flex flex-col gap-1 px-3 py-2",
          "rounded-lg border transition-all duration-200",
          "shrink-0 min-w-[160px] max-w-[220px]",
          "group relative overflow-hidden",
          isRecent ? [
            // Recent bookmarks - more prominent style
            "bg-gradient-to-br from-primary/5 to-primary/10",
            "border-primary/20 hover:border-primary/40",
            "hover:shadow-md hover:shadow-primary/10",
            "hover:-translate-y-0.5",
          ] : [
            // Older bookmarks - subtle style
            "bg-muted/30 border-border/50",
            "hover:bg-muted/50 hover:border-border",
            "hover:shadow-sm",
          ]
        )}
      >
        {/* Recent indicator */}
        {isRecent && (
          <div className="absolute top-1 right-1">
            <SparklesIcon className="w-3 h-3 text-primary/60" />
          </div>
        )}

        {/* Content preview */}
        <span className={cn(
          "truncate font-medium leading-tight text-sm",
          isRecent ? "text-foreground" : "text-foreground/80"
        )}>
          {preview || "(empty)"}
        </span>

        {/* Time */}
        {timeStr && (
          <span className={cn(
            "text-[10px]",
            isRecent ? "text-primary/70" : "text-muted-foreground"
          )}>
            {timeStr}
          </span>
        )}
      </Link>
    );
  };

  return (
    <div className={cn("w-full", className)}>
      {/* Bookmarks Section */}
      <div className="rounded-xl bg-gradient-to-r from-muted/40 via-muted/30 to-muted/40 border border-border/50 p-3">
        {/* Header */}
        <div className="flex items-center justify-between mb-2">
          <div className="flex items-center gap-2">
            <div className="p-1.5 rounded-lg bg-primary/10">
              <BookmarkIcon className="w-4 h-4 text-primary" />
            </div>
            <span className="text-sm font-semibold text-foreground">
              {t("common.bookmarks" as any) || "Bookmarks"}
            </span>
            <span className="text-xs text-muted-foreground px-1.5 py-0.5 rounded-full bg-muted/50">
              {pinnedMemos.length}
            </span>
          </div>
        </div>

        {/* Recent Bookmarks */}
        {recentMemos.length > 0 && (
          <div className="mb-2">
            <div className="flex items-center gap-1.5 mb-2">
              <SparklesIcon className="w-3 h-3 text-primary/70" />
              <span className="text-xs font-medium text-primary/80">
                {t("common.recent" as any) || "Recent"}
              </span>
            </div>
            <div className="flex flex-row items-stretch gap-2 overflow-x-auto pb-1 scrollbar-thin scrollbar-thumb-muted scrollbar-track-transparent">
              {recentMemos.map((memo) => renderBookmarkCard(memo, true))}
            </div>
          </div>
        )}

        {/* Older Bookmarks - Collapsible */}
        {olderMemos.length > 0 && (
          <div>
            <button
              onClick={() => setShowOlder(!showOlder)}
              className={cn(
                "flex items-center gap-1.5 text-xs text-muted-foreground",
                "hover:text-foreground transition-colors py-1 px-1 -ml-1 rounded",
                "hover:bg-muted/50"
              )}
            >
              {showOlder ? (
                <ChevronDownIcon className="w-3 h-3" />
              ) : (
                <ChevronRightIcon className="w-3 h-3" />
              )}
              <span>
                {showOlder
                  ? (t("common.hide-older" as any) || "Hide older")
                  : `${olderMemos.length} ${t("common.older-bookmarks" as any) || "older bookmarks"}`
                }
              </span>
            </button>

            {showOlder && (
              <div className="flex flex-row items-stretch gap-2 overflow-x-auto pt-2 pb-1 scrollbar-thin scrollbar-thumb-muted scrollbar-track-transparent">
                {olderMemos.map((memo) => renderBookmarkCard(memo, false))}
              </div>
            )}
          </div>
        )}

        {/* If all bookmarks are recent, just show them */}
        {recentMemos.length === 0 && olderMemos.length > 0 && !showOlder && (
          <div className="flex flex-row items-stretch gap-2 overflow-x-auto pb-1 scrollbar-thin scrollbar-thumb-muted scrollbar-track-transparent">
            {olderMemos.slice(0, 5).map((memo) => renderBookmarkCard(memo, false))}
            {olderMemos.length > 5 && (
              <button
                onClick={() => setShowOlder(true)}
                className={cn(
                  "flex items-center justify-center px-4 py-2",
                  "rounded-lg border border-dashed border-muted-foreground/30",
                  "text-xs text-muted-foreground hover:text-foreground",
                  "hover:border-muted-foreground/50 hover:bg-muted/30",
                  "transition-all duration-200 shrink-0"
                )}
              >
                +{olderMemos.length - 5} {t("common.more") || "more"}
              </button>
            )}
          </div>
        )}
      </div>
    </div>
  );
};

export default PinnedSection;
