"use client";

import { useRouter } from "next/navigation";
import { useState } from "react";
import { safeInternalLink } from "@/lib/links";

interface Props {
  id: number;
  content: string | null;
  link: string | null;
  isRead: boolean;
  createdAt: string;
}

// R14 B.4: row keeps its single-tap "mark-read + navigate" behaviour but
// also shows a small Delete button. The button stops event propagation so
// it doesn't trigger the row's click handler.
export default function NotificationRow({ id, content, link, isRead, createdAt }: Props) {
  const router = useRouter();
  const [pending, setPending] = useState(false);
  const [deleting, setDeleting] = useState(false);
  const [deleted, setDeleted] = useState(false);

  async function handleClick() {
    if (pending) return;
    setPending(true);
    try {
      if (!isRead) {
        // Best-effort; don't block navigation on a failed mark-read.
        fetch("/api/notifications/read", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ id }),
        }).catch(() => {});
      }
      if (link) router.push(safeInternalLink(link));
      else router.refresh();
    } finally {
      setPending(false);
    }
  }

  async function handleDelete(e: React.MouseEvent) {
    e.stopPropagation();
    if (deleting || deleted) return;
    setDeleting(true);
    try {
      const res = await fetch(`/api/notifications/${id}`, { method: "DELETE" });
      if (res.ok) {
        setDeleted(true);
        router.refresh();
      }
    } finally {
      setDeleting(false);
    }
  }

  if (deleted) return null;

  const className = `w-full text-left rounded-lg p-4 transition-colors ${
    isRead ? "bg-surface hover:bg-surface-light" : "bg-surface-light border-l-4 border-primary hover:brightness-110"
  } ${link ? "cursor-pointer" : "cursor-default"}`;

  return (
    <div className="relative group">
      <button
        type="button"
        onClick={handleClick}
        className={className + " w-full"}
        disabled={!link && isRead}
      >
        <div className="flex items-start justify-between gap-4 pr-8">
          <div className="flex-1 min-w-0">
            <p className="text-text-muted mt-1">{content}</p>
          </div>
          <p className="text-text-muted text-sm shrink-0">
            {new Date(createdAt).toLocaleDateString()}
          </p>
        </div>
      </button>
      <button
        type="button"
        onClick={handleDelete}
        disabled={deleting}
        aria-label="Delete notification"
        className="absolute top-2 right-2 p-1.5 rounded text-text-muted hover:text-red-400 hover:bg-surface transition-colors opacity-60 group-hover:opacity-100 focus:opacity-100 disabled:opacity-30"
      >
        <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
        </svg>
      </button>
    </div>
  );
}
