import { Link } from '@tanstack/react-router'
import type { Garden } from '@/lib/gardens'
import { formatDimensions } from '@/lib/units'
import { cardActionClass, cardDangerClass } from '@/components/ui/cardActions'

/**
 * One garden as a card: the body links into the editor. The footer differs by
 * role — the owner gets Share / Copy / Edit / Delete; a recipient sees a
 * "shared · role" badge and a Leave action (garden metadata edit, sharing and
 * copying are owner-only).
 * Ownership is the authoritative ownerId==me check, not the my_role hint.
 */
export function GardenCard({
  garden,
  currentUserId,
  onShare,
  onCopy,
  onEdit,
  onDelete,
  onLeave,
}: {
  garden: Garden
  currentUserId?: number
  onShare: () => void
  onCopy: () => void
  onEdit: () => void
  onDelete: () => void
  onLeave: () => void
}) {
  const owner = currentUserId != null && garden.ownerId === currentUserId
  return (
    <div className="flex flex-col rounded-xl border border-border bg-surface transition-colors hover:border-accent/50">
      <Link
        to="/gardens/$gardenId"
        params={{ gardenId: String(garden.id) }}
        className="flex-1 rounded-t-xl p-4 outline-none focus-visible:ring-2 focus-visible:ring-accent/40"
      >
        <div className="flex items-center gap-2">
          <h3 className="truncate font-semibold text-fg">{garden.name}</h3>
          {!owner && garden.myRole && (
            <span className="shrink-0 rounded bg-border/60 px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wide text-muted">
              shared · {garden.myRole}
            </span>
          )}
        </div>
        <p className="mt-1 text-sm text-muted">
          {formatDimensions(garden.widthCm, garden.heightCm, garden.unitPref)}
        </p>
        {garden.notes && <p className="mt-2 line-clamp-2 text-sm text-muted">{garden.notes}</p>}
      </Link>
      <div className="flex justify-end gap-1 border-t border-border px-2 py-1.5">
        {owner ? (
          <>
            <button type="button" onClick={onShare} className={cardActionClass}>
              Share
            </button>
            <button type="button" onClick={onCopy} className={cardActionClass}>
              Copy
            </button>
            <button type="button" onClick={onEdit} className={cardActionClass}>
              Edit
            </button>
            <button type="button" onClick={onDelete} className={cardDangerClass}>
              Delete
            </button>
          </>
        ) : (
          <button type="button" onClick={onLeave} className={cardDangerClass}>
            Leave
          </button>
        )}
      </div>
    </div>
  )
}
