"use client";

import { useRouter } from "next/navigation";
import { useSavedMessages, useSdk } from "@lynkd/messaging-inbox-sdk";
import { Header } from "@/components/nav/Header";
import { Avatar } from "@/components/ui/primitives";
import { RichText } from "@/lib/rich-text";
import { relativeTime } from "@/lib/format";
import { Bookmark, Hash } from "lucide-react";

export function SavedView() {
  const { messages, loading } = useSavedMessages();
  const { userById, channelById } = useSdk();
  const router = useRouter();

  return (
    <div className="flex min-w-0 flex-1 flex-col">
      <Header eyebrow="Messaging" title="Saved items" subtitle="Messages you bookmarked for later" />
      <div className="min-h-0 flex-1 overflow-y-auto p-4">
        {loading && <div className="py-10 text-center text-muted">Loading…</div>}
        {!loading && messages.length === 0 && (
          <div className="flex flex-col items-center gap-2 py-20 text-muted">
            <Bookmark size={34} className="text-dim" />
            <div className="text-[15px] font-semibold text-ink">No saved items yet</div>
            <div className="text-[13px]">Hover a message and hit the bookmark icon to save it here.</div>
          </div>
        )}
        <div className="mx-auto max-w-3xl space-y-2">
          {messages.map((m) => {
            const author = userById(m.authorId);
            const ch = m.channelId ? channelById(m.channelId) : undefined;
            return (
              <button
                key={m.id}
                onClick={() => ch && router.push(`/c/${ch.id}`)}
                className="flex w-full items-start gap-3 rounded-card border border-border bg-panel p-3.5 text-left transition-colors hover:border-border-strong"
              >
                {author && <Avatar user={author} size={34} showPresence={false} />}
                <div className="min-w-0 flex-1">
                  <div className="flex items-center gap-2 text-[12.5px]">
                    <b>{author?.name}</b>
                    {ch && <span className="flex items-center gap-0.5 text-muted"><Hash size={11} /> {ch.name}</span>}
                    <span className="ml-auto text-[11px] text-dim">{relativeTime(m.ts)}</span>
                  </div>
                  <div className="mt-0.5 line-clamp-2 text-[13.5px] text-ink/85"><RichText text={m.body} /></div>
                </div>
                <Bookmark size={15} className="mt-1 shrink-0 fill-accent text-accent" />
              </button>
            );
          })}
        </div>
      </div>
    </div>
  );
}
