"use client";

import {
  Box,
  Chip,
  Checkbox,
  Link as MuiLink,
  Paper,
  Tab,
  Tabs,
  Typography,
} from "@mui/material";
import { useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { ItemLotTraceResponse } from "@/app/api/itemTracing";
import ItemTracingDocLink from "./ItemTracingDocLink";
import ItemTracingLotTraceLink from "./ItemTracingLotTraceLink";
import { createTraceLabelTranslator, qcItemLabel } from "./traceLabelUtils";
import { formatNum, formatQty } from "./traceQtyUtils";
import { normalizeTargetDateForLink } from "./traceDocLinkUtils";
import type { CompiledTraceGraph } from "./compileTraceGraph";
import { buildTracePresentationRows } from "./tracePresentationAdapter";
import {
  hasMultipleLocations,
  mergeScopedAdjustments,
  mergeScopedOrigins,
  mergeScopedOutboundUsage,
  mergeScopedQcResults,
  mergeScopedStockTakeEvents,
  mergeScopedTransfers,
} from "./mergeLocationScopedData";
import {
  resolveStockTakeAcceptedQty,
  resolveStockTakeBookQty,
} from "./traceStockTakeUtils";
import {
  FilterableDataTable,
  type FilterableColumnDef,
} from "./itemTracingTableFilters";

type TraceParams = { stockInLineId?: number; lotNo?: string; itemCode?: string };

type Props = {
  data: ItemLotTraceResponse;
  compiledGraph: CompiledTraceGraph;
  onTrace?: (params: TraceParams) => void;
};

/** FP-MTMS Version Checklist | Functions Ref. No. 17 | v1.0.1 | 2026-07-20 */
const ItemTracingSections: React.FC<Props> = ({ data, compiledGraph, onTrace }) => {
  const { t } = useTranslation("itemTracing");
  const [tab, setTab] = useState(0);
  const { bomTrace, joPrelude, lot } = data;
  const tr = useMemo(() => createTraceLabelTranslator(t), [t]);

  const presentationRows = useMemo(
    () => buildTracePresentationRows(compiledGraph.nodes, data),
    [compiledGraph.nodes, data],
  );

  const multiLocation = hasMultipleLocations(data);
  const mergedOrigins = useMemo(() => mergeScopedOrigins(data), [data]);
  const mergedQc = useMemo(() => mergeScopedQcResults(data), [data]);
  const mergedOutbound = useMemo(() => mergeScopedOutboundUsage(data), [data]);
  const mergedStockTake = useMemo(() => mergeScopedStockTakeEvents(data), [data]);
  const mergedAdjustments = useMemo(() => mergeScopedAdjustments(data), [data]);
  const mergedTransfers = useMemo(() => mergeScopedTransfers(data), [data]);

  const stockUom = lot.uom;

  const tabKeys = useMemo(() => {
    const keys = [
      "origins",
      "qc",
      "outbound",
      "stockTake",
      "adjustments",
      "transfers",
      "bom",
    ] as const;
    if (joPrelude) {
      return [...keys, "joPick"] as const;
    }
    return keys;
  }, [joPrelude]);

  const activeTab = tabKeys[tab] ?? tabKeys[0];

  const bomDirectionLabel =
    bomTrace.direction === "FINISHED_GOOD"
      ? t("bomDirectionFG")
      : bomTrace.direction === "MATERIAL"
        ? t("bomDirectionMaterial")
        : t("bomDirectionUnknown");

  const useJoMaterialInputs = joPrelude != null && joPrelude.materialInputs.length > 0;

  const checkboxCellFromStatus = (
    status?: string | null,
    opts?: { checkedWhen?: Array<string>; rejectedWhen?: Array<string> },
  ): React.ReactNode => {
    const s = String(status || "").trim().toLowerCase();
    const checkedWhen = opts?.checkedWhen ?? [];
    const rejectedWhen = opts?.rejectedWhen ?? [];

    const isRejected = rejectedWhen.includes(s);
    const isChecked = checkedWhen.includes(s);

    if (isRejected) {
      return (
        <Checkbox
          checked
          disabled
          readOnly
          size="small"
          sx={{ color: "error.main", "&.Mui-checked": { color: "error.main" } }}
        />
      );
    }
    if (isChecked) {
      return (
        <Checkbox
          checked
          disabled
          readOnly
          size="small"
          sx={{ color: "success.main", "&.Mui-checked": { color: "success.main" } }}
        />
      );
    }
    return <Checkbox checked={false} disabled readOnly size="small" />;
  };

  const originCols = useMemo((): FilterableColumnDef<(typeof mergedOrigins)[number]>[] => {
    const cols: FilterableColumnDef<(typeof mergedOrigins)[number]>[] = [];
    if (multiLocation) {
      cols.push({
        key: "warehouse",
        label: t("warehouse"),
        value: (o) => o.scopeWarehouseCode,
      });
    }
    cols.push(
      {
        key: "type",
        label: t("type"),
        value: (o) => tr.refType(o.type),
      },
      {
        key: "ref",
        label: t("ref"),
        value: (o) => o.refCode || "—",
        cell: (o) =>
          o.type === "PO" ? (
            <ItemTracingDocLink kind="po" code={o.refCode} id={o.refId} />
          ) : o.type === "JO" ? (
            <ItemTracingDocLink kind="jo" code={o.refCode} id={o.refId} />
          ) : (
            o.refCode || "—"
          ),
      },
      {
        key: "supplier",
        label: t("supplier"),
        value: (o) => [o.supplierCode, o.supplierName].filter(Boolean).join(" "),
      },
      { key: "dnNo", label: t("dnNo"), value: (o) => o.dnNo || "—" },
      {
        key: "qty",
        label: t("qty"),
        align: "right",
        value: (o) => formatQty(o.acceptedQty, stockUom),
      },
      {
        key: "status",
        label: t("status"),
        value: (o) => tr.stockInStatus(o.status),
      },
      {
        key: "timestamp",
        label: t("timestamp"),
        value: (o) => o.receiptDate ?? "—",
      },
    );
    return cols;
  }, [multiLocation, t, tr, stockUom]);

  const qcCols = useMemo((): FilterableColumnDef<(typeof mergedQc)[number]>[] => {
    const cols: FilterableColumnDef<(typeof mergedQc)[number]>[] = [];
    if (multiLocation) {
      cols.push({
        key: "warehouse",
        label: t("warehouse"),
        value: (q) => q.scopeWarehouseCode,
      });
    }
    cols.push(
      {
        key: "status",
        label: t("status"),
        value: (q) => (q.qcPassed ? t("qcPassed") : t("qcFailed")),
        cell: (q) => (
          <Chip
            size="small"
            color={q.qcPassed ? "success" : "error"}
            label={q.qcPassed ? t("qcPassed") : t("qcFailed")}
          />
        ),
      },
      {
        key: "criteria",
        label: t("detailQcCriteria"),
        value: (q) => qcItemLabel(q) || "—",
      },
      {
        key: "acceptedQty",
        label: t("acceptedQty"),
        align: "right",
        value: (q) => formatQty(q.acceptedQty, stockUom),
      },
      {
        key: "failQty",
        label: t("failQty"),
        align: "right",
        value: (q) => formatQty(q.failQty, stockUom),
      },
      {
        key: "remarks",
        label: t("remarks"),
        value: (q) => q.remarks?.trim() || "",
      },
      {
        key: "handler",
        label: t("handler"),
        value: (q) => q.handledBy || "—",
      },
      {
        key: "timestamp",
        label: t("timestamp"),
        value: (q) => q.created ?? "—",
      },
    );
    return cols;
  }, [multiLocation, t, stockUom]);

  const outboundCols = useMemo((): FilterableColumnDef<(typeof mergedOutbound)[number]>[] => {
    const cols: FilterableColumnDef<(typeof mergedOutbound)[number]>[] = [];
    if (multiLocation) {
      cols.push({
        key: "warehouse",
        label: t("warehouse"),
        value: (u) => u.scopeWarehouseCode,
      });
    }
    cols.push(
      {
        key: "type",
        label: t("type"),
        value: (u) => tr.usageType(u.usageType),
      },
      {
        key: "qty",
        label: t("qty"),
        align: "right",
        value: (u) => formatQty(u.qty, stockUom),
      },
      {
        key: "pickOrder",
        label: t("pickOrder"),
        value: (u) => u.pickOrderCode || u.consoCode || "—",
        cell: (u) => (
          <ItemTracingDocLink
            kind="pick"
            code={u.pickOrderCode}
            id={u.pickOrderId}
            consoCode={u.consoCode}
          />
        ),
      },
      {
        key: "jobOrder",
        label: t("jobOrder"),
        value: (u) => u.jobOrderCode || "—",
        cell: (u) => (
          <ItemTracingDocLink kind="jo" code={u.jobOrderCode} id={u.jobOrderId} />
        ),
      },
      {
        key: "deliveryOrder",
        label: t("deliveryOrder"),
        value: (u) => u.deliveryOrderCode || "—",
      },
      {
        key: "handler",
        label: t("handler"),
        value: (u) => u.handler || "—",
      },
      {
        key: "timestamp",
        label: t("timestamp"),
        value: (u) => u.timestamp ?? "—",
      },
    );
    return cols;
  }, [multiLocation, t, tr, stockUom]);

  const stockTakeCols = useMemo((): FilterableColumnDef<(typeof mergedStockTake)[number]>[] => {
    const cols: FilterableColumnDef<(typeof mergedStockTake)[number]>[] = [];
    if (multiLocation) {
      cols.push({
        key: "warehouse",
        label: t("warehouse"),
        value: (e) => e.scopeWarehouseCode,
      });
    }
    cols.push(
      { key: "ref", label: t("ref"), value: (e) => e.stockTakeCode },
      {
        key: "round",
        label: t("detailStockTakeRound"),
        value: (e) =>
          e.stockTakeRoundName?.trim() ||
          (e.stockTakeRoundId != null ? `#${e.stockTakeRoundId}` : "—"),
      },
      {
        key: "section",
        label: t("detailStockTakeSection"),
        value: (e) => e.stockTakeSection?.trim() || "—",
      },
      {
        key: "location",
        label: t("detailLocation"),
        value: (e) => e.warehouseCode?.trim() || "—",
      },
      {
        key: "lotNo",
        label: t("lotNo"),
        value: (e) => e.lotNo?.trim() || data.lot.lotNo || "—",
      },
      {
        key: "before",
        label: t("before"),
        align: "right",
        value: (e) =>
          formatQty(
            resolveStockTakeBookQty(e.recordDetail, e.beforeQty),
            stockUom,
          ),
      },
      {
        key: "after",
        label: t("after"),
        align: "right",
        value: (e) =>
          formatQty(
            resolveStockTakeAcceptedQty(e.recordDetail, e.afterQty),
            stockUom,
          ),
      },
      {
        key: "variance",
        label: t("variance"),
        align: "right",
        value: (e) =>
          formatQty(
            e.recordDetail?.varianceQty != null
              ? e.recordDetail.varianceQty
              : e.varianceQty,
            stockUom,
          ),
      },
      {
        key: "approver",
        label: t("approver"),
        value: (e) => e.approver || "—",
      },
      {
        key: "timestamp",
        label: t("timestamp"),
        value: (e) => e.timestamp ?? "—",
      },
    );
    return cols;
  }, [multiLocation, t, stockUom, data.lot.lotNo]);

  const adjustmentCols = useMemo((): FilterableColumnDef<(typeof mergedAdjustments)[number]>[] => {
    const cols: FilterableColumnDef<(typeof mergedAdjustments)[number]>[] = [];
    if (multiLocation) {
      cols.push({
        key: "warehouse",
        label: t("warehouse"),
        value: (a) => a.scopeWarehouseCode,
      });
    }
    cols.push(
      {
        key: "type",
        label: t("type"),
        value: (a) => a.adjustmentType,
      },
      {
        key: "direction",
        label: `${t("directionIn")}/${t("directionOut")}`,
        value: (a) => a.direction,
      },
      {
        key: "qty",
        label: t("qty"),
        align: "right",
        value: (a) => formatQty(a.qty, stockUom),
      },
      {
        key: "ref",
        label: t("ref"),
        value: (a) => a.refCode || "—",
      },
      {
        key: "remarks",
        label: t("remarks"),
        value: (a) => a.reason?.trim() || "",
      },
      {
        key: "handler",
        label: t("handler"),
        value: (a) => a.handledBy || "—",
      },
      {
        key: "timestamp",
        label: t("timestamp"),
        value: (a) => a.timestamp ?? "—",
      },
    );
    return cols;
  }, [multiLocation, t, stockUom]);

  const transferCols = useMemo((): FilterableColumnDef<(typeof mergedTransfers)[number]>[] => {
    const cols: FilterableColumnDef<(typeof mergedTransfers)[number]>[] = [];
    if (multiLocation) {
      cols.push({
        key: "warehouse",
        label: t("warehouse"),
        value: (row) => row.scopeWarehouseCode,
      });
    }
    cols.push(
      {
        key: "from",
        label: t("from"),
        value: (row) => row.fromWarehouse || "—",
      },
      {
        key: "to",
        label: t("to"),
        value: (row) => row.toWarehouse || "—",
      },
      {
        key: "qty",
        label: t("qty"),
        align: "right",
        value: (row) => formatQty(row.qty, stockUom),
      },
      {
        key: "timestamp",
        label: t("timestamp"),
        value: (row) => row.timestamp ?? "—",
      },
    );
    return cols;
  }, [multiLocation, t, stockUom]);

  type JoMaterialInput = NonNullable<typeof joPrelude>["materialInputs"][number];
  type BomUpstream = (typeof bomTrace.upstream)[number];

  const bomUpstreamJoCols = useMemo((): FilterableColumnDef<JoMaterialInput>[] => [
    {
      key: "jobOrder",
      label: t("jobOrder"),
      value: (m) => m.jobOrderCode || "—",
      cell: (m) => (
        <ItemTracingDocLink kind="jo" code={m.jobOrderCode} id={m.jobOrderId} />
      ),
    },
    { key: "material", label: t("itemCode"), value: (m) => m.materialItemCode },
    { key: "materialLot", label: t("itemLot"), value: (m) => m.materialLotNo },
    {
      key: "pickOrder",
      label: t("pickOrder"),
      value: (m) => m.pickOrderCode || m.consoCode || "—",
      cell: (m) =>
        m.pickOrderCode ? (
          <ItemTracingDocLink
            kind="pick"
            code={m.pickOrderCode}
            id={m.pickOrderId}
            consoCode={m.consoCode}
          />
        ) : (
          "—"
        ),
    },
    {
      key: "pickedAt",
      label: t("pickedAt"),
      value: (m) => m.pickedAt ?? "—",
    },
    {
      key: "materialQty",
      label: t("materialQty"),
      align: "right",
      value: (m) => formatNum(Number(m.materialQty)),
    },
    {
      key: "qtyPerUnit",
      label: t("qtyPerUnit"),
      align: "right",
      value: (m) =>
        m.bomQtyPerUnit != null ? formatNum(Number(m.bomQtyPerUnit)) : "—",
    },
    {
      key: "uom",
      label: t("uom"),
      value: (m) => m.materialUom?.trim() || "",
    },
    {
      key: "processingStatus",
      label: t("processingStatus"),
      align: "center",
      value: (m) => tr.processingStatus(m.processingStatus),
      cell: (m) =>
        checkboxCellFromStatus(m.processingStatus, {
          checkedWhen: ["completed"],
          rejectedWhen: ["rejected"],
        }),
    },
    {
      key: "matchStatus",
      label: t("matchStatus"),
      align: "center",
      value: (m) => tr.matchStatus(m.matchStatus),
      cell: (m) => checkboxCellFromStatus(m.matchStatus, { checkedWhen: ["completed"] }),
    },
    {
      key: "trace",
      label: "",
      value: () => "",
      cell: (m) =>
        m.materialLotNo && onTrace ? (
          <MuiLink
            component="button"
            type="button"
            variant="body2"
            underline="hover"
            onClick={() =>
              onTrace({
                lotNo: m.materialLotNo,
                itemCode: m.materialItemCode,
              })
            }
          >
            {t("traceMaterialLot")}
          </MuiLink>
        ) : (
          "—"
        ),
    },
  ], [t, tr, stockUom, onTrace]);

  const bomUpstreamCols = useMemo((): FilterableColumnDef<BomUpstream>[] => [
    {
      key: "jobOrder",
      label: t("jobOrder"),
      value: (u) => u.jobOrderCode || "—",
      cell: (u) => (
        <ItemTracingDocLink kind="jo" code={u.jobOrderCode} id={u.jobOrderId} />
      ),
    },
    { key: "material", label: t("itemCode"), value: (u) => u.materialItemCode },
    { key: "materialLot", label: t("itemLot"), value: (u) => u.materialLotNo },
    {
      key: "materialQty",
      label: t("materialQty"),
      align: "right",
      value: (u) => formatNum(Number(u.materialQty)),
    },
    {
      key: "qtyPerUnit",
      label: t("qtyPerUnit"),
      align: "right",
      value: (u) =>
        u.bomQtyPerUnit != null ? formatNum(Number(u.bomQtyPerUnit)) : "—",
    },
    {
      key: "uom",
      label: t("uom"),
      value: () => stockUom,
    },
  ], [t, stockUom]);

  const bomDownstreamCols = useMemo((): FilterableColumnDef<(typeof bomTrace.downstream)[number]>[] => [
    {
      key: "jobOrder",
      label: t("jobOrder"),
      value: (d) => d.jobOrderCode || "—",
      cell: (d) => (
        <ItemTracingDocLink kind="jo" code={d.jobOrderCode} id={d.jobOrderId} />
      ),
    },
    { key: "finishedItem", label: t("itemCode"), value: (d) => d.finishedItemCode },
    { key: "finishedLot", label: t("itemLot"), value: (d) => d.finishedLotNo },
    {
      key: "fgQty",
      label: t("fgQty"),
      align: "right",
      value: (d) => formatQty(d.fgQty, d.fgUom?.trim() || ""),
    },
    {
      key: "materialQty",
      label: t("materialQty"),
      align: "right",
      value: (d) => formatQty(d.materialQtyUsed, stockUom),
    },
  ], [t, stockUom]);

  const bomRecipeCols = useMemo((): FilterableColumnDef<(typeof bomTrace.bomRecipe)[number]>[] => [
    { key: "material", label: t("itemCode"), value: (r) => r.materialItemCode },
    {
      key: "materialName",
      label: t("detailItemName"),
      value: (r) => r.materialItemName,
    },
    {
      key: "qtyPerUnit",
      label: t("qtyPerUnit"),
      align: "right",
      value: (r) => formatNum(Number(r.qtyPerUnit)),
    },
    { key: "uom", label: t("uom"), value: (r) => r.uom },
  ], [t]);

  type JoPickRow = (typeof presentationRows.joPicks)[number];
  const joPickCols = useMemo((): FilterableColumnDef<JoPickRow>[] => [
    {
      key: "pickOrder",
      label: t("pickOrder"),
      value: (row) => row.pickOrderCode || row.consoCode || "—",
      cell: (row) =>
        row.pickOrderCode ? (
          <ItemTracingDocLink
            kind="jodetail"
            code={row.pickOrderCode}
            id={row.pickOrderId}
            consoCode={row.consoCode || row.pickOrderCode}
            targetDate={normalizeTargetDateForLink(
              row.targetDate || row.pickedAt,
            )}
            openInNewTab
          />
        ) : (
          "—"
        ),
    },
    { key: "material", label: t("Item"), value: (row) => row.materialItemCode },
    {
      key: "lotNo",
      label: t("lotNo"),
      value: (row) => row.materialLotNo || "—",
      cell: (row) =>
        row.materialLotNo ? (
          <ItemTracingLotTraceLink
            label={row.materialLotNo}
            lotNo={row.materialLotNo}
            itemCode={row.materialItemCode}
            variant="body2"
          />
        ) : (
          "—"
        ),
    },
    {
      key: "pickedQty",
      label: t("pickedQty"),
      align: "right",
      value: (row) => formatQty(row.qty, row.uom || stockUom),
    },
    {
      key: "assignedStep",
      label: t("detailAssignedStep"),
      value: (row) => row.assignedStepName || "—",
    },
    {
      key: "timestamp",
      label: t("timestamp"),
      value: (row) => row.pickedAt ?? "—",
    },
  ], [t, stockUom]);

  type JoPickLine = NonNullable<typeof joPrelude>["pickOrders"][number]["lines"][number];
  const joPickLineCols = useMemo((): FilterableColumnDef<JoPickLine>[] => [
    {
      key: "material",
      label: t("Item"),
      value: (line) =>
        line.itemName ? `${line.itemCode} · ${line.itemName}` : line.itemCode,
    },
    {
      key: "plannedQty",
      label: t("requiredQty"),
      align: "right",
      value: (line) => formatQty(Number(line.requiredQty), stockUom),
    },
    {
      key: "pickedQty",
      label: t("pickedQty"),
      align: "right",
      value: (line) => formatQty(Number(line.pickedQty), stockUom),
    },
    { key: "status", label: t("status"), value: (line) => tr.pickStatus(line.status) },
  ], [t, tr, stockUom]);

  return (
    <Paper variant="outlined">
      <Tabs
        value={tab}
        onChange={(_, v) => setTab(v)}
        variant="scrollable"
        scrollButtons="auto"
      >
        <Tab label={t("tabOrigins")} />
        <Tab label={t("tabQc")} />
        <Tab label={t("tabOutbound")} />
        <Tab label={t("tabStockTake")} />
        <Tab label={t("tabAdjustments")} />
        <Tab label={t("tabTransfers")} />
        <Tab label={t("tabBom")} />
        {joPrelude && <Tab label={t("tabJoPick")} />}
      </Tabs>
      <Box sx={{ p: 2, overflowX: "auto" }}>
        {multiLocation && (
          <Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
            {t("sectionsMultiLocationHint")}
          </Typography>
        )}
        {activeTab === "origins" && (
          <FilterableDataTable
            rows={mergedOrigins}
            columns={originCols}
            getRowKey={(o) => `${o.inventoryLotId}-${o.stockInLineId}`}
            emptyLabel={t("noRecords")}
          />
        )}

        {activeTab === "qc" && (
          <FilterableDataTable
            rows={mergedQc}
            columns={qcCols}
            getRowKey={(q) => q.rowKey}
            emptyLabel={t("noRecords")}
          />
        )}

        {activeTab === "outbound" && (
          <FilterableDataTable
            rows={mergedOutbound}
            columns={outboundCols}
            getRowKey={(u) => `${u.inventoryLotId}-${u.stockOutLineId}`}
            emptyLabel={t("noRecords")}
          />
        )}

        {activeTab === "stockTake" && (
          <FilterableDataTable
            rows={mergedStockTake}
            columns={stockTakeCols}
            getRowKey={(e) => e.rowKey}
            emptyLabel={t("noRecords")}
          />
        )}

        {activeTab === "adjustments" && (
          <FilterableDataTable
            rows={mergedAdjustments}
            columns={adjustmentCols}
            getRowKey={(a) => a.rowKey}
            emptyLabel={t("noRecords")}
          />
        )}

        {activeTab === "transfers" && (
          <FilterableDataTable
            rows={mergedTransfers}
            columns={transferCols}
            getRowKey={(row) => row.rowKey}
            emptyLabel={t("noRecords")}
          />
        )}

        {activeTab === "bom" && (
          <Box>
            <Typography variant="body2" color="text.secondary" gutterBottom>
              {t("bomDirection")}: <strong>{bomDirectionLabel}</strong>
            </Typography>

            <Typography variant="subtitle2" sx={{ mt: 2, mb: 1 }}>
              {t("bomUpstream")}
            </Typography>
            <Box sx={{ mb: 2 }}>
              {useJoMaterialInputs ? (
                <FilterableDataTable
                  rows={joPrelude!.materialInputs}
                  columns={bomUpstreamJoCols}
                  getRowKey={(_, i) => `up-jo-${i}`}
                  emptyLabel={t("noRecords")}
                />
              ) : (
                <FilterableDataTable
                  rows={bomTrace.upstream}
                  columns={bomUpstreamCols}
                  getRowKey={(_, i) => `up-${i}`}
                  emptyLabel={t("noRecords")}
                />
              )}
            </Box>

            <Typography variant="subtitle2" sx={{ mb: 1 }}>
              {t("bomDownstream")}
            </Typography>
            <Box sx={{ mb: 2 }}>
              <FilterableDataTable
                rows={bomTrace.downstream}
                columns={bomDownstreamCols}
                getRowKey={(_, i) => `down-${i}`}
                emptyLabel={t("noRecords")}
              />
            </Box>

            <Typography variant="subtitle2" sx={{ mb: 1 }}>
              {t("bomRecipe")}
            </Typography>
            <FilterableDataTable
              rows={bomTrace.bomRecipe}
              columns={bomRecipeCols}
              getRowKey={(_, i) => `recipe-${i}`}
              emptyLabel={t("noRecords")}
            />
          </Box>
        )}

        {activeTab === "joPick" && joPrelude && (
          <Box>
            {presentationRows.joPicks.length > 0 ? (
              <FilterableDataTable
                rows={presentationRows.joPicks}
                columns={joPickCols}
                getRowKey={(row) => row.id}
                emptyLabel={t("noRecords")}
              />
            ) : joPrelude.pickOrders.length === 0 ? (
              <Typography color="text.secondary" variant="body2">
                {t("noRecords")}
              </Typography>
            ) : (
              joPrelude.pickOrders.map((po) => (
                <Box key={po.pickOrderId} sx={{ mb: 3 }}>
                  <Typography variant="subtitle2" gutterBottom>
                    <ItemTracingDocLink
                      kind="jodetail"
                      code={po.pickOrderCode}
                      id={po.pickOrderId}
                      consoCode={po.consoCode || po.pickOrderCode}
                      targetDate={normalizeTargetDateForLink(po.targetDate)}
                      openInNewTab
                    />
                    {" · "}
                    <Chip
                      size="small"
                      label={tr.pickStatus(po.status)}
                      variant="outlined"
                      sx={{ ml: 0.5 }}
                    />
                  </Typography>
                  <Typography
                    variant="caption"
                    color="text.secondary"
                    display="block"
                    sx={{ mb: 1 }}
                  >
                    {[
                      po.targetDate && `${t("targetDate")}: ${po.targetDate}`,
                      po.completeDate && `${t("completeDate")}: ${po.completeDate}`,
                    ]
                      .filter(Boolean)
                      .join(" · ")}
                  </Typography>
                  <FilterableDataTable
                    rows={po.lines}
                    columns={joPickLineCols}
                    getRowKey={(line) => String(line.pickOrderLineId)}
                    emptyLabel={t("noRecords")}
                  />
                </Box>
              ))
            )}
          </Box>
        )}
      </Box>
    </Paper>
  );
};

export default ItemTracingSections;
