"use client";

import Link from "next/link";
import { formatDistanceToNow } from "date-fns";
import type { NotificationInboxItem } from "@alqove/api-client";
import { useMarkNotificationRead } from "@/lib/queries/use-notifications";

const ICONS: Record<NotificationInboxItem["icon"], string> = {
  package: "📦",
  truck: "🚚",
  check: "✓",
  alert: "⚠",
  x: "✕",
  "package-return": "↩",
  message: "💬",
};

export function NotificationRow({ item }: { item: NotificationInboxItem }) {
  const markRead = useMarkNotificationRead();
  const unread = item.read_at === null;

  const handleClick = () => {
    if (unread) markRead.mutate(item.id);
  };

  return (
    <Link
      href={item.cta_url}
      onClick={handleClick}
      className={`flex gap-3 px-4 py-3 hover:bg-bone/60 border-b border-forest/10 ${
        unread ? "bg-forest/5" : ""
      }`}
    >
      <span className="text-xl leading-none shrink-0" aria-hidden>
        {ICONS[item.icon] ?? "•"}
      </span>
      <div className="flex-1 min-w-0">
        <div className="flex items-center justify-between gap-2">
          <span className={`text-sm ${unread ? "font-semibold" : "font-medium"} text-forest truncate`}>
            {item.title}
          </span>
          {unread ? (
            <span className="h-2 w-2 rounded-full bg-terracotta shrink-0" aria-label="unread" />
          ) : null}
        </div>
        <p className="text-xs text-forest/70 truncate">{item.body}</p>
        <p className="text-[11px] text-forest/50 mt-0.5">
          {formatDistanceToNow(new Date(item.created_at), { addSuffix: true })}
        </p>
      </div>
    </Link>
  );
}
