import { createFileRoute, Link, useParams } from "@tanstack/react-router";
import { useQuery } from "@tanstack/react-query";
import { useServerFn } from "@tanstack/react-start";
import { ArrowLeft, Bell } from "lucide-react";
import { getNotification } from "@/lib/notifications.functions";
import { formatDate } from "@/lib/format";
import { Skeleton } from "@/components/ui/skeleton";
import { Button } from "@/components/ui/button";

export const Route = createFileRoute("/app/notifications/$id")({
  head: () => ({
    meta: [
      { title: "Message — Billsline" },
      { name: "description", content: "Read your full Billsline notification message and offer details." },
      { property: "og:title", content: "Message — Billsline" },
      { property: "og:description", content: "Read your full Billsline notification message and offer details." },
    ],
  }),
  component: NotificationDetail,
});

function NotificationDetail() {
  const { id } = useParams({ from: "/app/notifications/$id" });
  const fetchOne = useServerFn(getNotification);
  const { data, isPending, error } = useQuery({
    queryKey: ["notification", id],
    queryFn: () => fetchOne({ data: { id } }),
  });

  const n = data as
    | { title: string; body: string | null; created_at: string; link: string | null; metadata: { image_url?: string } | null }
    | undefined;
  const image = n?.metadata?.image_url;

  return (
    <div className="space-y-3 p-3 pb-8">
      <Link to="/app/notifications" className="inline-flex items-center gap-1 text-sm text-muted-foreground">
        <ArrowLeft className="h-4 w-4" /> Notifications
      </Link>

      {isPending ? (
        <Skeleton className="h-64 w-full rounded-2xl" />
      ) : error ? (
        <p className="py-16 text-center text-sm text-muted-foreground">This message is no longer available.</p>
      ) : n ? (
        <article className="overflow-hidden rounded-2xl bg-card shadow-card ring-1 ring-border/40">
          {image ? (
            <img src={image} alt="" className="h-44 w-full object-cover" />
          ) : (
            <div className="grid h-24 place-items-center bg-gradient-primary">
              <Bell className="h-8 w-8 text-primary-foreground" />
            </div>
          )}
          <div className="space-y-2 p-4">
            <h1 className="text-lg font-bold leading-snug">{n.title}</h1>
            <p className="text-[11px] text-muted-foreground">{formatDate(n.created_at)}</p>
            {n.body && <p className="whitespace-pre-wrap text-sm leading-relaxed text-foreground/90">{n.body}</p>}
            {n.link && n.link.startsWith("/") && (
              <Button asChild className="mt-2 w-full">
                <a href={n.link}>Open</a>
              </Button>
            )}
          </div>
        </article>
      ) : null}
    </div>
  );
}
