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

interface BookmarksSectionProps {
    className?: string;
}

// Max items to show when expanded
const MAX_VISIBLE = 5;

const BookmarksSection = ({ className }: BookmarksSectionProps) => {
    const t = useTranslate();
    const user = useCurrentUser();
    // Default COLLAPSED
    const [isOpen, setIsOpen] = useState(false);
    const [showAll, setShowAll] = useState(false);

    // Build simple filter for pinned memos - NO context filters
    const pinnedFilter = useMemo(() => {
        if (user?.name) {
            const userId = user.name.split("/")[1];
            return `creator_id == ${userId} && pinned`;
        }
        return "pinned";
    }, [user?.name]);

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

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

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

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

    // 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 "now";
        if (diffHours < 24) return `${diffHours}h`;
        return `${diffDays}d`;
    };

    const visibleMemos = showAll ? pinnedMemos : pinnedMemos.slice(0, MAX_VISIBLE);
    const hiddenCount = pinnedMemos.length - MAX_VISIBLE;

    return (
        <div className={cn("w-full", className)}>
            {/* Collapsible Header */}
            <button
                onClick={() => setIsOpen(!isOpen)}
                className={cn(
                    "w-full flex items-center justify-between py-2 px-1",
                    "hover:bg-muted/40 rounded-md transition-colors",
                    "group cursor-pointer"
                )}
            >
                <div className="flex items-center gap-1.5">
                    {isOpen ? (
                        <ChevronDownIcon className="w-4 h-4 text-muted-foreground" />
                    ) : (
                        <ChevronRightIcon className="w-4 h-4 text-muted-foreground" />
                    )}
                    <BookmarkIcon className="w-4 h-4 text-primary/70" />
                    <span className="text-sm font-medium text-foreground/80">
                        {t("common.bookmarks" as any) || "Bookmarks"}
                    </span>
                </div>
                <span className="text-xs text-muted-foreground bg-muted/50 px-1.5 py-0.5 rounded-full">
                    {pinnedMemos.length}
                </span>
            </button>

            {/* Bookmark List - Only show when expanded */}
            {isOpen && (
                <div className="flex flex-col gap-0.5 mt-1 pl-5">
                    {visibleMemos.map((memo) => {
                        const memoPath = memo.name.startsWith("memos/") ? memo.name : `memos/${memo.name}`;
                        const preview = getPreview(memo.content || "");
                        const time = formatTime(memo);

                        return (
                            <MemoHoverCard key={memo.name} content={memo.content || ""}>
                                <Link
                                    to={`/${memoPath}`}
                                    className={cn(
                                        "flex items-center justify-between",
                                        "px-2 py-1.5 rounded-md",
                                        "hover:bg-muted/60 transition-colors",
                                        "group"
                                    )}
                                >
                                    <span className="text-sm text-foreground/70 group-hover:text-foreground truncate flex-1 mr-2">
                                        {preview}
                                    </span>
                                    {time && (
                                        <span className="text-[10px] text-muted-foreground shrink-0">
                                            {time}
                                        </span>
                                    )}
                                </Link>
                            </MemoHoverCard>
                        );
                    })}

                    {/* Show More / Show Less */}
                    {hiddenCount > 0 && (
                        <button
                            onClick={(e) => {
                                e.stopPropagation();
                                setShowAll(!showAll);
                            }}
                            className={cn(
                                "flex items-center gap-1 px-2 py-1.5",
                                "text-xs text-muted-foreground hover:text-foreground",
                                "transition-colors rounded-md hover:bg-muted/40"
                            )}
                        >
                            {showAll ? (
                                <>
                                    <ChevronDownIcon className="w-3 h-3" />
                                    <span>{t("common.hide-older" as any) || "Show less"}</span>
                                </>
                            ) : (
                                <>
                                    <ChevronRightIcon className="w-3 h-3" />
                                    <span>+{hiddenCount} {t("common.more" as any) || "more"}</span>
                                </>
                            )}
                        </button>
                    )}
                </div>
            )}
        </div>
    );
};

export default BookmarksSection;

