"use client";

import Link from "next/link";
import MuiLink from "@mui/material/Link";
import { isWorkbenchTicketNo, normalizeTargetDateForLink } from "./traceDocLinkUtils";

type DocLinkProps = {
  kind: "jo" | "po" | "pick" | "workbench" | "jodetail";
  code: string;
  id?: number | null;
  consoCode?: string;
  ticketNo?: string;
  targetDate?: string;
  /** Finished Good Record tab on /doworkbench (default: 3 = all). */
  workbenchTab?: number;
  /** Completed JO pick record tab on /jodetail (default: 1 = complete records). */
  jodetailTab?: number;
  /** Open in a new browser tab (used for links inside the flow graph). */
  openInNewTab?: boolean;
};

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

/** FP-MTMS Version Checklist | Functions Ref. No. 16 | v1.0.1 | 2026-07-19 */
const ItemTracingDocLink: React.FC<DocLinkProps> = ({
  kind,
  code,
  id,
  consoCode,
  ticketNo,
  targetDate,
  workbenchTab = 3,
  jodetailTab = 1,
  openInNewTab = false,
}) => {
  if (!code?.trim()) return <>—</>;

  const linkTargetDate = normalizeTargetDateForLink(targetDate);

  let href = "#";
  if (kind === "jo" && id) href = `/jo/edit?id=${id}`;
  else if (kind === "po" && id) href = `/po/edit?id=${id}`;
  else if (kind === "workbench" && ticketNo?.trim()) {
    const params = new URLSearchParams();
    params.set("tab", String(workbenchTab));
    params.set("ticketNo", ticketNo.trim());
    if (linkTargetDate) params.set("targetDate", linkTargetDate);
    // Only Item Tracing deep-links should auto-open detail (not DO finish redirect).
    params.set("openDetail", "1");
    href = `/doworkbench?${params.toString()}`;
  } else if (kind === "jodetail" && (consoCode || code)) {
    const params = new URLSearchParams();
    params.set("tab", String(jodetailTab));
    // Prefer PI-* pick order code for jodetail search; consoCode may be PICK-*.
    params.set("pickOrderCode", (code || consoCode || "").trim());
    if (linkTargetDate) params.set("targetDate", linkTargetDate);
    params.set("openDetail", "1");
    href = `/jodetail?${params.toString()}`;
  } else if (kind === "pick") {
    // /pickOrder/detail?consoCode=… is retired — only link when we have a TI-* workbench ticket.
    const workbenchTicket = [ticketNo, consoCode, code]
      .map((v) => (v ?? "").trim())
      .find(isWorkbenchTicketNo);
    if (workbenchTicket) {
      const params = new URLSearchParams();
      params.set("tab", String(workbenchTab));
      params.set("ticketNo", workbenchTicket);
      if (linkTargetDate) params.set("targetDate", linkTargetDate);
      params.set("openDetail", "1");
      href = `/doworkbench?${params.toString()}`;
    } else {
      return <>{code}</>;
    }
  } else {
    return <>{code}</>;
  }

  return (
    <MuiLink
      component={Link}
      href={href}
      underline="hover"
      {...(openInNewTab ? { target: "_blank", rel: "noopener noreferrer" } : {})}
      onClick={openInNewTab ? stopGraphEvent : undefined}
      onMouseDown={openInNewTab ? stopGraphEvent : undefined}
    >
      {code}
    </MuiLink>
  );
};

export default ItemTracingDocLink;
