"use client";

import Link from "next/link";
import MuiLink, { type LinkProps as MuiLinkProps } from "@mui/material/Link";
import { buildItemTracingHref } from "./traceNavigationUtils";

type Props = {
  label: string;
  lotNo?: string;
  itemCode?: string;
  stockInLineId?: number;
  /** Prevent React Flow node selection when the link sits on a graph card. */
  stopPropagation?: boolean;
  variant?: MuiLinkProps["variant"];
  sx?: MuiLinkProps["sx"];
};

const stopGraphEvent = (e: React.MouseEvent) => {
  e.stopPropagation();
};

const ItemTracingLotTraceLink: React.FC<Props> = ({
  label,
  lotNo,
  itemCode,
  stockInLineId,
  stopPropagation = false,
  variant = "caption",
  sx,
}) => {
  if (!lotNo?.trim() && stockInLineId == null) return null;

  return (
    <MuiLink
      component={Link}
      href={buildItemTracingHref({ lotNo, itemCode, stockInLineId })}
      underline="hover"
      target="_blank"
      rel="noopener noreferrer"
      variant={variant}
      sx={sx}
      onClick={stopPropagation ? stopGraphEvent : undefined}
      onMouseDown={stopPropagation ? stopGraphEvent : undefined}
    >
      {label}
    </MuiLink>
  );
};

export default ItemTracingLotTraceLink;
