"use client";

import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
  Autocomplete,
  Box,
  Button,
  Collapse,
  Dialog,
  DialogContent,
  DialogTitle,
  FormControl,
  IconButton,
  MenuItem,
  Paper,
  Select,
  Stack,
  TablePagination,
  Tooltip,
  Typography,
} from "@mui/material";
import CalendarTodayIcon from "@mui/icons-material/CalendarToday";
import FilterListIcon from "@mui/icons-material/FilterList";
import InfoOutlinedIcon from "@mui/icons-material/InfoOutlined";
import ReceiptLongIcon from "@mui/icons-material/ReceiptLong";
import StorefrontIcon from "@mui/icons-material/Storefront";
import { Add, Close, Delete, KeyboardArrowDown, KeyboardArrowRight } from "@mui/icons-material";
import { DatePicker, LocalizationProvider } from "@mui/x-date-pickers";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
import dayjs, { Dayjs } from "dayjs";
import { useTranslation } from "react-i18next";
import type { TFunction } from "i18next";
import Swal, { type SweetAlertOptions } from "sweetalert2";
import {
  DoDetail,
  DoDetailLine,
  DoReplenishmentRecord,
  fetchDoDetail,
  fetchDoReplenishmentList,
  fetchDoSearch,
  submitDoReplenishment,
} from "@/app/api/do/actions";
import { arrayToDateString } from "@/app/utils/formatUtil";
import {
  REPLENISHMENT_FIELD_ICON_SX,
  REPLENISHMENT_AUTOCOMPLETE_SX,
  REPLENISHMENT_FILLED_SELECT_SX,
  REPLENISHMENT_TABLE_SX,
  REPLENISHMENT_FIELD_BUTTON_SX,
  REPLENISHMENT_LOOKUP_BUTTON_SX,
  REPLENISHMENT_OUTLINED_ACTION_BUTTON_SX,
  REPLENISHMENT_SOURCE_HEADER_SX,
  REPLENISHMENT_TEXTFIELD_SX,
  ReplenishmentFieldLabelSpacer,
  ReplenishmentFilterField,
  ReplenishmentReadonlyValue,
  ReplenishmentTextField,
} from "./ReplenishmentFilterField";

export type ReplenishmentStatus = "pending" | "processing" | "completed";

export type ReplenishmentReasonCode = "quality_issue" | "out_of_stock" | "other";

const REPLENISHMENT_REASON_CODES: readonly ReplenishmentReasonCode[] = [
  "quality_issue",
  "out_of_stock",
  "other",
];

function isReplenishmentReasonCode(value: string): value is ReplenishmentReasonCode {
  return (REPLENISHMENT_REASON_CODES as readonly string[]).includes(value);
}

function formatReplenishmentReason(reason: string | undefined, t: TFunction): string {
  const trimmed = reason?.trim();
  if (!trimmed) return "—";
  if (isReplenishmentReasonCode(trimmed)) {
    return t(`replenishmentReason.${trimmed}`);
  }
  return trimmed;
}

function fireReplenishmentAlert(t: TFunction, options: SweetAlertOptions) {
  return Swal.fire({
    confirmButtonText: t("Confirm"),
    ...options,
  });
}

export type ReplenishmentDraftRow = {
  rowId: string;
  deliveryDate: string;
  sourceDoId: number;
  sourceDoCode: string;
  sourceDoLineId: number;
  itemId?: number;
  itemNo: string;
  itemName: string;
  originalQty: number;
  replenishQty: number;
  shortUom?: string;
  shopCode?: string;
  shopName?: string;
  truckLaneCode?: string;
  reason?: string;
};

export type ReplenishmentRecord = ReplenishmentDraftRow & {
  id: number;
  code: string;
  targetDoId?: number;
  targetDoCode?: string;
  targetDoEstimatedArrivalDate?: string;
  pickOrderLineId?: number;
  actualPickQty?: number;
  relateTicketNo?: string;
  status: ReplenishmentStatus;
  created: string;
};

function resolveOriginalShipmentQty(line: DoDetailLine): number {
  if (line.actualShippedQty != null && Number.isFinite(Number(line.actualShippedQty))) {
    return Number(line.actualShippedQty);
  }
  return line.qty ?? 0;
}

function formatQtyWithUom(qty: number | undefined, uom?: string): string {
  const unit = uom?.trim();
  if (qty == null || Number.isNaN(qty)) {
    return unit ? `— ${unit}` : "—";
  }
  return unit ? `${qty} ${unit}` : String(qty);
}

function TrackingFieldBlock({
  label,
  value,
}: {
  label: string;
  value: React.ReactNode;
}) {
  return (
    <Box>
      <Typography
        variant="caption"
        color="text.secondary"
        fontWeight={600}
        sx={{ display: "block", lineHeight: 1.4, mb: 0.25 }}
      >
        {label}
      </Typography>
      <Typography variant="body2" sx={{ wordBreak: "break-word", lineHeight: 1.5 }}>
        {value ?? "—"}
      </Typography>
    </Box>
  );
}

function TrackingInlineLine({
  label,
  children,
}: {
  label: string;
  children: React.ReactNode;
}) {
  return (
    <Typography variant="body2" sx={{ wordBreak: "break-word", lineHeight: 1.6 }}>
      <Box component="span" sx={{ fontWeight: 600 }}>
        {label}：
      </Box>{" "}
      {children}
    </Typography>
  );
}

type SourceDoContext = {
  doId: number;
  doCode: string;
  shopCode?: string;
  shopName?: string;
  truckLaneCode?: string | null;
  status: string;
  lines: DoDetailLine[];
};

function mapApiRecord(record: DoReplenishmentRecord): ReplenishmentRecord {
  return {
    rowId: `record-${record.id}`,
    deliveryDate: record.deliveryDate,
    sourceDoId: record.sourceDoId,
    sourceDoCode: record.sourceDoCode ?? "",
    sourceDoLineId: record.sourceDoLineId,
    itemId: record.itemId,
    itemNo: record.itemNo ?? "",
    itemName: record.itemName ?? "",
    originalQty: record.originalQty != null ? Number(record.originalQty) : 0,
    replenishQty: Number(record.replenishQty),
    shortUom: record.shortUom,
    shopCode: record.shopCode,
    shopName: record.shopName,
    truckLaneCode: record.truckLaneCode,
    id: record.id,
    code: record.code,
    targetDoId: record.targetDoId,
    targetDoCode: record.targetDoCode,
    targetDoEstimatedArrivalDate: record.targetDoEstimatedArrivalDate,
    pickOrderLineId: record.pickOrderLineId,
    actualPickQty:
      record.actualPickQty != null && Number.isFinite(Number(record.actualPickQty))
        ? Number(record.actualPickQty)
        : undefined,
    relateTicketNo: record.relateTicketNo,
    status: record.status as ReplenishmentStatus,
    reason: record.reason,
    created: record.created ?? "",
  };
}

/** Shop code: partial match. Shop name: prefix match (e.g. first 4 characters). */
function matchesShopInput(detail: DoDetail, shopInput: string): boolean {
  const normalized = shopInput.trim().toLowerCase();
  if (!normalized) return false;
  const code = detail.shopCode?.toLowerCase() ?? "";
  const name = detail.shopName?.toLowerCase() ?? "";
  return code.includes(normalized) || name.startsWith(normalized);
}

function matchesDeliveryDate(
  estimatedArrivalDate: number[] | undefined,
  deliveryDateStr: string,
): boolean {
  if (!estimatedArrivalDate?.length) return false;
  return arrayToDateString(estimatedArrivalDate) === deliveryDateStr;
}

function lineUomDisplay(line?: DoDetailLine | null): string {
  if (!line) return "";
  return (line.shortUom ?? line.uomCode ?? line.uom ?? "").trim();
}

function filterSourceDoLinesByItemNo(
  lines: DoDetailLine[],
  inputValue: string,
): DoDetailLine[] {
  const query = inputValue.trim().toLowerCase();
  if (!query) return lines;
  return lines.filter((line) =>
    (line.itemNo ?? "").toLowerCase().includes(query),
  );
}

function filterSourceDoLinesByItemName(
  lines: DoDetailLine[],
  inputValue: string,
): DoDetailLine[] {
  const query = inputValue.trim().toLowerCase();
  if (!query) return lines;
  return lines.filter((line) =>
    (line.itemName ?? "").toLowerCase().includes(query),
  );
}

function sourceDoLineNameLabel(line: DoDetailLine): string {
  return (line.itemName ?? line.itemNo ?? "").trim();
}

type DraftDoGroup = {
  sourceDoId: number;
  sourceDoCode: string;
  rows: ReplenishmentDraftRow[];
};

type DraftShopGroup = {
  shopKey: string;
  shopCode: string;
  shopName?: string;
  dos: DraftDoGroup[];
};

type DraftLaneGroup = {
  laneKey: string;
  truckLaneCode: string;
  shops: DraftShopGroup[];
};

function draftShopGroupKey(row: ReplenishmentDraftRow): string {
  return row.shopCode?.trim() || row.shopName?.trim() || "—";
}

function draftLaneGroupKey(row: ReplenishmentDraftRow): string {
  return row.truckLaneCode?.trim() || "";
}

function formatDraftShopDisplay(shopGroup: DraftShopGroup): string {
  const name = shopGroup.shopName?.trim();
  const code = shopGroup.shopCode?.trim();
  if (code && name) return `${code} - ${name}`;
  return name || code || shopGroup.shopKey;
}

function groupDraftRowsByShopAndDo(rows: ReplenishmentDraftRow[]): DraftShopGroup[] {
  const shopMap = new Map<string, DraftShopGroup>();

  for (const row of rows) {
    const shopKey = draftShopGroupKey(row);
    let shopGroup = shopMap.get(shopKey);
    if (!shopGroup) {
      shopGroup = {
        shopKey,
        shopCode: row.shopCode?.trim() || "",
        shopName: row.shopName,
        dos: [],
      };
      shopMap.set(shopKey, shopGroup);
    }

    let doGroup = shopGroup.dos.find((group) => group.sourceDoId === row.sourceDoId);
    if (!doGroup) {
      doGroup = {
        sourceDoId: row.sourceDoId,
        sourceDoCode: row.sourceDoCode,
        rows: [],
      };
      shopGroup.dos.push(doGroup);
    }
    doGroup.rows.push(row);
  }

  return Array.from(shopMap.values())
    .sort((a, b) => a.shopKey.localeCompare(b.shopKey, undefined, { numeric: true }))
    .map((shopGroup) => ({
      ...shopGroup,
      dos: shopGroup.dos
        .sort((a, b) =>
          a.sourceDoCode.localeCompare(b.sourceDoCode, undefined, { numeric: true }),
        )
        .map((doGroup) => ({
          ...doGroup,
          rows: [...doGroup.rows],
        })),
    }));
}

function draftLaneCollapseKey(laneKey: string): string {
  return laneKey || "__truck_x__";
}

function draftShopCollapseKey(laneKey: string, shopKey: string): string {
  return `${draftLaneCollapseKey(laneKey)}::${shopKey}`;
}

function draftDoCollapseKey(laneKey: string, shopKey: string, sourceDoId: number): string {
  return `${draftShopCollapseKey(laneKey, shopKey)}::${sourceDoId}`;
}

function toggleCollapsedKey(
  setter: React.Dispatch<React.SetStateAction<Set<string>>>,
  key: string,
) {
  setter((prev) => {
    const next = new Set(prev);
    if (next.has(key)) next.delete(key);
    else next.add(key);
    return next;
  });
}

type DraftPreviewCollapseHeaderProps = {
  collapsed: boolean;
  onToggle: () => void;
  label: string;
  title: React.ReactNode;
  titleVariant?: "subtitle2" | "body2";
  titleTooltip?: string;
};

function DraftPreviewCollapseHeader({
  collapsed,
  onToggle,
  label,
  title,
  titleVariant = "subtitle2",
  titleTooltip,
}: DraftPreviewCollapseHeaderProps) {
  const titleNode = (
    <Typography
      variant={titleVariant}
      fontWeight={titleVariant === "subtitle2" ? 700 : 600}
      sx={{
        wordBreak: "break-word",
        lineHeight: 1.4,
        ...(titleVariant === "subtitle2"
          ? {
              display: "-webkit-box",
              WebkitLineClamp: 2,
              WebkitBoxOrient: "vertical",
              overflow: "hidden",
            }
          : { wordBreak: "break-all" }),
      }}
    >
      {title}
    </Typography>
  );

  return (
    <Stack
      direction="row"
      spacing={0.5}
      alignItems="flex-start"
      onClick={onToggle}
      sx={{ cursor: "pointer", userSelect: "none" }}
    >
      <IconButton
        size="small"
        onClick={(event) => {
          event.stopPropagation();
          onToggle();
        }}
        sx={{ p: 0.25, mt: -0.25, flexShrink: 0 }}
        aria-expanded={!collapsed}
      >
        {collapsed ? (
          <KeyboardArrowRight fontSize="small" />
        ) : (
          <KeyboardArrowDown fontSize="small" />
        )}
      </IconButton>
      <Box sx={{ minWidth: 0, flex: 1 }}>
        <Typography variant="caption" color="text.secondary" display="block">
          {label}
        </Typography>
        {titleTooltip ? (
          <Tooltip title={titleTooltip} placement="top" arrow>
            {titleNode}
          </Tooltip>
        ) : (
          titleNode
        )}
      </Box>
    </Stack>
  );
}

function groupDraftRowsByLaneShopAndDo(rows: ReplenishmentDraftRow[]): DraftLaneGroup[] {
  const laneBuckets = new Map<string, ReplenishmentDraftRow[]>();

  for (const row of rows) {
    const laneKey = draftLaneGroupKey(row);
    const bucket = laneBuckets.get(laneKey) ?? [];
    bucket.push(row);
    laneBuckets.set(laneKey, bucket);
  }

  return Array.from(laneBuckets.entries())
    .sort(([a], [b]) => a.localeCompare(b, undefined, { numeric: true }))
    .map(([laneKey, laneRows]) => ({
      laneKey,
      truckLaneCode: laneKey,
      shops: groupDraftRowsByShopAndDo(laneRows),
    }));
}

const DoReplenishmentTab: React.FC = () => {
  const { t } = useTranslation("do");
  const inFlightRef = useRef(false);
  const itemCodeInputRef = useRef<HTMLInputElement | null>(
    null,
  ) as React.MutableRefObject<HTMLInputElement | null>;
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isLookingUp, setIsLookingUp] = useState(false);

  const [deliveryDate, setDeliveryDate] = useState<Dayjs | null>(dayjs());
  const [doCodeSuffix, setDoCodeSuffix] = useState("");
  const [shopInput, setShopInput] = useState("");
  const [sourceDo, setSourceDo] = useState<SourceDoContext | null>(null);
  const [selectedLine, setSelectedLine] = useState<DoDetailLine | null>(null);
  const [replenishQtyInput, setReplenishQtyInput] = useState("");
  const [replenishReasonInput, setReplenishReasonInput] = useState<ReplenishmentReasonCode | "">(
    "",
  );

  const [draftRows, setDraftRows] = useState<ReplenishmentDraftRow[]>([]);
  const [collapsedLaneKeys, setCollapsedLaneKeys] = useState<Set<string>>(() => new Set());
  const [collapsedShopKeys, setCollapsedShopKeys] = useState<Set<string>>(() => new Set());
  const [collapsedDoKeys, setCollapsedDoKeys] = useState<Set<string>>(() => new Set());
  const [records, setRecords] = useState<ReplenishmentRecord[]>([]);
  const [isLoadingTracking, setIsLoadingTracking] = useState(false);
  const [trackStatusFilter, setTrackStatusFilter] = useState<ReplenishmentStatus | "all">("all");
  const [trackDateFilter, setTrackDateFilter] = useState<Dayjs | null>(null);
  const [trackPage, setTrackPage] = useState(0);
  const [trackRowsPerPage, setTrackRowsPerPage] = useState(10);
  const [trackingDialogOpen, setTrackingDialogOpen] = useState(false);

  const deliveryDateStr = deliveryDate?.format("YYYY-MM-DD") ?? "";

  const handleLookupSourceDo = useCallback(async () => {
    const suffix = doCodeSuffix.trim();
    const shop = shopInput.trim();
    if (suffix.length !== 4) {
      await fireReplenishmentAlert(t,{
        icon: "warning",
        title: t("DO code suffix must be exactly 4 characters"),
      });
      return;
    }
    if (!deliveryDateStr) {
      await fireReplenishmentAlert(t,{ icon: "warning", title: t("Delivery date is required") });
      return;
    }
    if (!shop) {
      await fireReplenishmentAlert(t,{ icon: "warning", title: t("Shop code or name is required") });
      return;
    }
    setIsLookingUp(true);
    try {
      const searchRes = await fetchDoSearch(
        suffix,
        shop,
        "completed",
        "",
        "",
        `${deliveryDateStr}T00:00:00`,
        "",
        1,
        100,
        undefined,
        null,
        null,
      );
      const candidates = searchRes.records.filter(
        (r) =>
          r.code.endsWith(suffix) &&
          matchesDeliveryDate(r.estimatedArrivalDate, deliveryDateStr),
      );
      if (candidates.length === 0) {
        await fireReplenishmentAlert(t,{ icon: "error", title: t("Source DO not found") });
        setSourceDo(null);
        return;
      }
      const details = await Promise.all(candidates.map((c) => fetchDoDetail(c.id)));
      const matched = details.filter((d) => matchesShopInput(d, shop));
      if (matched.length === 0) {
        await fireReplenishmentAlert(t,{ icon: "error", title: t("Source DO not found") });
        setSourceDo(null);
        return;
      }
      if (matched.length > 1) {
        await fireReplenishmentAlert(t,{
          icon: "error",
          title: t("Multiple source DOs matched"),
          text: t("Please verify DO code suffix, delivery date and shop."),
        });
        setSourceDo(null);
        return;
      }
      const detail = matched[0];
      const matchedCandidate = candidates.find((c) => c.id === detail.id);
      const resolvedTruckLaneCode =
        detail.truckLaneCode?.trim() || matchedCandidate?.truckLanceCode?.trim() || null;
      if (detail.status !== "completed") {
        await fireReplenishmentAlert(t,{
          icon: "error",
          title: t("Source DO must be completed"),
          text: t("Only completed delivery orders can be used as replenishment source."),
        });
        setSourceDo(null);
        return;
      }
      setSourceDo({
        doId: detail.id,
        doCode: detail.code,
        shopCode: detail.shopCode,
        shopName: detail.shopName,
        truckLaneCode: resolvedTruckLaneCode,
        status: detail.status,
        lines: detail.deliveryOrderLines ?? [],
      });
      setSelectedLine(null);
      setReplenishQtyInput("");
      setReplenishReasonInput("");
    } catch {
      await fireReplenishmentAlert(t,{ icon: "error", title: t("Failed to lookup source DO") });
    } finally {
      setIsLookingUp(false);
    }
  }, [deliveryDateStr, doCodeSuffix, shopInput, t]);

  const handleAddDraftRow = useCallback(() => {
    if (!sourceDo) {
      void fireReplenishmentAlert(t,{ icon: "warning", title: t("Please lookup source DO first") });
      return;
    }
    if (!deliveryDateStr) {
      void fireReplenishmentAlert(t,{ icon: "warning", title: t("Delivery date is required") });
      return;
    }
    if (!selectedLine) {
      void fireReplenishmentAlert(t,{ icon: "warning", title: t("Please select an item") });
      return;
    }
    const qty = Number(replenishQtyInput);
    if (!Number.isFinite(qty) || qty <= 0) {
      void fireReplenishmentAlert(t,{ icon: "warning", title: t("Replenish qty must be greater than zero") });
      return;
    }
    const line = selectedLine;

    const existingRowIndex = draftRows.findIndex(
      (r) => r.sourceDoLineId === line.id && r.sourceDoId === sourceDo.doId,
    );

    const reason = replenishReasonInput || undefined;
    if (existingRowIndex >= 0) {
      setDraftRows((prev) =>
        prev.map((row, index) =>
          index === existingRowIndex
            ? {
                ...row,
                replenishQty: row.replenishQty + qty,
                reason: row.reason?.trim() || reason,
              }
            : row,
        ),
      );
    } else {
      setDraftRows((prev) => [
        ...prev,
        {
          rowId: `draft-${Date.now()}-${prev.length}`,
          deliveryDate: deliveryDateStr,
          sourceDoId: sourceDo.doId,
          sourceDoCode: sourceDo.doCode,
          sourceDoLineId: line.id,
          itemNo: line.itemNo ?? "",
          itemName: line.itemName ?? line.itemNo ?? "",
          originalQty: resolveOriginalShipmentQty(line),
          replenishQty: qty,
          shortUom: lineUomDisplay(line) || undefined,
          shopCode: sourceDo.shopCode,
          shopName: sourceDo.shopName,
          truckLaneCode: sourceDo.truckLaneCode?.trim() || undefined,
          reason,
        },
      ]);
    }
    setSelectedLine(null);
    setReplenishQtyInput("");
    setReplenishReasonInput("");
    window.setTimeout(() => itemCodeInputRef.current?.focus(), 0);
  }, [
    deliveryDateStr,
    draftRows,
    replenishQtyInput,
    replenishReasonInput,
    selectedLine,
    sourceDo,
    t,
  ]);

  const handleRemoveDraftRow = useCallback((rowId: string) => {
    setDraftRows((prev) => prev.filter((r) => r.rowId !== rowId));
  }, []);

  const handleClearDraftRows = useCallback(() => {
    setDraftRows([]);
    setCollapsedLaneKeys(new Set());
    setCollapsedShopKeys(new Set());
    setCollapsedDoKeys(new Set());
  }, []);

  const handleSubmit = useCallback(async () => {
    if (inFlightRef.current) return;
    if (draftRows.length === 0) {
      await fireReplenishmentAlert(t,{ icon: "warning", title: t("No draft rows to submit") });
      return;
    }
    inFlightRef.current = true;
    setIsSubmitting(true);
    try {
      const created = await submitDoReplenishment(
        draftRows.map((row) => ({
          deliveryDate: row.deliveryDate,
          sourceDoId: row.sourceDoId,
          sourceDoLineId: row.sourceDoLineId,
          replenishQty: row.replenishQty,
          truckLaneCode: row.truckLaneCode,
          reason: row.reason?.trim() || undefined,
        })),
      );
      setDraftRows([]);
      await fireReplenishmentAlert(t,{
        icon: "success",
        title: t("Replenishment submitted successfully"),
        text: created.map((row) => row.code).join(", "),
      });
    } catch (error: unknown) {
      const message =
        error instanceof Error ? error.message : t("Failed to submit replenishment");
      await fireReplenishmentAlert(t,{ icon: "error", title: message });
    } finally {
      setIsSubmitting(false);
      inFlightRef.current = false;
    }
  }, [draftRows, t]);

  const loadTrackingRecords = useCallback(async () => {
    setIsLoadingTracking(true);
    try {
      const data = await fetchDoReplenishmentList({
        deliveryDate: trackDateFilter?.format("YYYY-MM-DD"),
        status: trackStatusFilter,
      });
      setRecords(data.map(mapApiRecord));
      setTrackPage(0);
    } catch {
      await fireReplenishmentAlert(t,{ icon: "error", title: t("Failed to load replenishment records") });
    } finally {
      setIsLoadingTracking(false);
    }
  }, [trackDateFilter, trackStatusFilter, t]);

  useEffect(() => {
    if (trackingDialogOpen) {
      void loadTrackingRecords();
    }
  }, [trackingDialogOpen, loadTrackingRecords]);

  const selectedLineUom = lineUomDisplay(selectedLine);

  const paginatedTrackRecords = useMemo(() => {
    const start = trackPage * trackRowsPerPage;
    return records.slice(start, start + trackRowsPerPage);
  }, [records, trackPage, trackRowsPerPage]);

  const datePickerSlotProps = useMemo(
    () => ({
      textField: {
        size: "small" as const,
        fullWidth: true,
        variant: "filled" as const,
        placeholder: t("replenishmentDatePlaceholder"),
        sx: REPLENISHMENT_TEXTFIELD_SX,
        InputProps: { disableUnderline: true },
      },
    }),
    [t],
  );

  const groupedDraftByLane = useMemo(
    () => groupDraftRowsByLaneShopAndDo(draftRows),
    [draftRows],
  );

  const currentDoDraftRows = useMemo(
    () =>
      sourceDo
        ? draftRows.filter((row) => row.sourceDoId === sourceDo.doId)
        : [],
    [draftRows, sourceDo],
  );

  const draftPreviewPanel = (
    <Paper
      variant="outlined"
      sx={{
        p: 2,
        height: "100%",
        display: "flex",
        flexDirection: "column",
        bgcolor: (theme) => (theme.palette.mode === "dark" ? "grey.900" : "common.white"),
      }}
    >
      <Stack spacing={0.5} sx={{ mb: 1.5 }}>
        <Typography variant="subtitle2" fontWeight={700}>
          {t("Draft List")}
          {draftRows.length > 0 ? ` (${draftRows.length})` : ""}
        </Typography>
        <Typography variant="caption" color="text.secondary">
          {t("Replenishment preview hint")}
        </Typography>
      </Stack>

      {draftRows.length === 0 ? (
        <Box
          sx={{
            flex: 1,
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            minHeight: 120,
            border: (theme) => `1px dashed ${theme.palette.divider}`,
            borderRadius: 2,
            px: 2,
          }}
        >
          <Typography variant="body2" color="text.secondary" textAlign="center">
            {t("Replenishment preview empty")}
          </Typography>
        </Box>
      ) : (
        <Stack
          spacing={1.5}
          sx={{
            flex: 1,
            minHeight: 0,
            maxHeight: { xs: 360, lg: "calc(100vh - 280px)" },
            overflowY: "auto",
            overflowX: "hidden",
            pr: 0.25,
            pb: 1.5,
            "& > *": { flexShrink: 0 },
          }}
        >
          {groupedDraftByLane.map((laneGroup) => {
            const laneDisplay = laneGroup.truckLaneCode || t("Truck X");
            const laneCollapseKey = draftLaneCollapseKey(laneGroup.laneKey);
            const laneCollapsed = collapsedLaneKeys.has(laneCollapseKey);
            return (
              <Paper
                key={laneCollapseKey}
                variant="outlined"
                sx={{
                  p: 1.5,
                  flexShrink: 0,
                  overflow: "visible",
                  bgcolor: (theme) =>
                    theme.palette.mode === "dark" ? "grey.800" : "grey.50",
                }}
              >
                <DraftPreviewCollapseHeader
                  collapsed={laneCollapsed}
                  onToggle={() => toggleCollapsedKey(setCollapsedLaneKeys, laneCollapseKey)}
                  label={t("Truck Lane")}
                  title={laneDisplay}
                  titleTooltip={laneDisplay}
                />

                <Collapse in={!laneCollapsed}>
                  <Stack spacing={1} sx={{ mt: 1 }}>
                  {laneGroup.shops.map((shopGroup) => {
                    const shopDisplay = formatDraftShopDisplay(shopGroup);
                    const shopCode = shopGroup.shopCode?.trim();
                    const shopCollapseKey = draftShopCollapseKey(
                      laneGroup.laneKey,
                      shopGroup.shopKey,
                    );
                    const shopCollapsed = collapsedShopKeys.has(shopCollapseKey);
                    return (
                      <Paper
                        key={`${laneGroup.laneKey}-${shopGroup.shopKey}`}
                        variant="outlined"
                        sx={{
                          p: 1.25,
                          flexShrink: 0,
                          overflow: "visible",
                          bgcolor: (theme) =>
                            theme.palette.mode === "dark" ? "grey.900" : "common.white",
                        }}
                      >
                        <DraftPreviewCollapseHeader
                          collapsed={shopCollapsed}
                          onToggle={() =>
                            toggleCollapsedKey(setCollapsedShopKeys, shopCollapseKey)
                          }
                          label={t("Shop Name")}
                          title={shopDisplay}
                          titleTooltip={
                            shopCode && shopGroup.shopName?.trim() ? shopCode : undefined
                          }
                        />

                        <Collapse in={!shopCollapsed}>
                          <Stack spacing={1} sx={{ mt: 1 }}>
                          {shopGroup.dos.map((doGroup) => {
                            const doCollapseKey = draftDoCollapseKey(
                              laneGroup.laneKey,
                              shopGroup.shopKey,
                              doGroup.sourceDoId,
                            );
                            const doCollapsed = collapsedDoKeys.has(doCollapseKey);
                            return (
                            <Box
                              key={`${laneGroup.laneKey}-${shopGroup.shopKey}-${doGroup.sourceDoId}`}
                              sx={(theme) => ({
                                border: `1px solid ${theme.palette.divider}`,
                                borderRadius: 1.5,
                                p: 1.25,
                                bgcolor:
                                  theme.palette.mode === "dark" ? "grey.800" : "grey.50",
                              })}
                            >
                              <DraftPreviewCollapseHeader
                                collapsed={doCollapsed}
                                onToggle={() =>
                                  toggleCollapsedKey(setCollapsedDoKeys, doCollapseKey)
                                }
                                label={t("Delivery Order Code")}
                                title={doGroup.sourceDoCode}
                                titleVariant="body2"
                                titleTooltip={doGroup.sourceDoCode}
                              />

                              <Collapse in={!doCollapsed}>
                              <Stack spacing={0.75} sx={{ mt: 1 }}>
                                {doGroup.rows.map((row) => {
                                  const qtyLabel = row.shortUom
                                    ? `${row.replenishQty} ${row.shortUom}`
                                    : String(row.replenishQty);
                                  return (
                                    <Box
                                      key={row.rowId}
                                      sx={(theme) => ({
                                        display: "flex",
                                        alignItems: "flex-start",
                                        gap: 1,
                                        py: 0.75,
                                        px: 1,
                                        borderRadius: 1,
                                        bgcolor:
                                          theme.palette.mode === "dark"
                                            ? "grey.900"
                                            : "common.white",
                                      })}
                                    >
                                      <Box sx={{ minWidth: 0, flex: 1 }}>
                                        <Stack
                                          direction="row"
                                          spacing={1}
                                          alignItems="flex-start"
                                          sx={{ mb: 0.25 }}
                                        >
                                          <Typography
                                            variant="body2"
                                            fontWeight={600}
                                            sx={{ flexShrink: 0, whiteSpace: "nowrap" }}
                                          >
                                            {row.itemNo}
                                          </Typography>
                                          <Typography
                                            variant="body2"
                                            color="text.secondary"
                                            sx={{
                                              minWidth: 0,
                                              flex: 1,
                                              lineHeight: 1.4,
                                              display: "-webkit-box",
                                              WebkitLineClamp: 2,
                                              WebkitBoxOrient: "vertical",
                                              overflow: "hidden",
                                            }}
                                          >
                                            {row.itemName}
                                          </Typography>
                                        </Stack>

                                        <Typography variant="body2">
                                          <Box component="span" color="text.secondary">
                                            {t("Replenish Qty")}:{" "}
                                          </Box>
                                          {qtyLabel}
                                        </Typography>
                                        {row.reason?.trim() ? (
                                          <Typography
                                            variant="body2"
                                            sx={{ mt: 0.25, wordBreak: "break-word" }}
                                          >
                                            <Box component="span" color="text.secondary">
                                              {t("Remark")}:{" "}
                                            </Box>
                                            {formatReplenishmentReason(row.reason, t)}
                                          </Typography>
                                        ) : null}
                                      </Box>

                                      <IconButton
                                        size="small"
                                        color="error"
                                        onClick={() => handleRemoveDraftRow(row.rowId)}
                                        aria-label={t("Delete")}
                                        sx={{ flexShrink: 0, mt: -0.25 }}
                                      >
                                        <Delete fontSize="small" />
                                      </IconButton>
                                    </Box>
                                  );
                                })}
                              </Stack>
                              </Collapse>
                            </Box>
                            );
                          })}
                          </Stack>
                        </Collapse>
                      </Paper>
                    );
                  })}
                  </Stack>
                </Collapse>
              </Paper>
            );
          })}
        </Stack>
      )}

      {draftRows.length > 0 && (
        <Stack direction="row" spacing={1} justifyContent="flex-end" sx={{ mt: 1.5 }}>
          <Button
            variant="outlined"
            color="inherit"
            onClick={handleClearDraftRows}
            sx={REPLENISHMENT_FIELD_BUTTON_SX}
          >
            {t("Clear")}
          </Button>
          <Button
            variant="contained"
            onClick={() => void handleSubmit()}
            disabled={isSubmitting}
            sx={REPLENISHMENT_FIELD_BUTTON_SX}
          >
            {t("Submit")}
          </Button>
        </Stack>
      )}
    </Paper>
  );

  return (
    <Stack spacing={2}>
      <Box
        sx={{
          display: "grid",
          gridTemplateColumns: { xs: "1fr", xl: "minmax(0, 1fr) minmax(300px, 380px)" },
          gap: 2,
          alignItems: "stretch",
        }}
      >
        <Paper
          variant="outlined"
          sx={{
            p: 2,
            minWidth: 0,
            bgcolor: (theme) => (theme.palette.mode === "dark" ? "grey.900" : "grey.50"),
          }}
        >
          <Stack spacing={2}>
          <Stack spacing={1.5}>
            <Box
              sx={{
                display: "grid",
                gridTemplateColumns: {
                  xs: "1fr",
                  sm: "repeat(2, minmax(0, 1fr))",
                  lg: "repeat(3, minmax(0, 1fr))",
                },
                gap: 2,
                alignItems: "start",
              }}
            >
              <ReplenishmentFilterField
                icon={<CalendarTodayIcon fontSize="small" sx={REPLENISHMENT_FIELD_ICON_SX} />}
                title={t("Estimated Arrival Date")}
                required
              >
                <LocalizationProvider dateAdapter={AdapterDayjs}>
                  <DatePicker
                    format="YYYY-MM-DD"
                    value={deliveryDate}
                    onChange={(v) => {
                      setDeliveryDate(v);
                      setSourceDo(null);
                    }}
                    slotProps={datePickerSlotProps}
                    sx={{ width: "100%" }}
                  />
                </LocalizationProvider>
              </ReplenishmentFilterField>

              <ReplenishmentFilterField
                icon={<ReceiptLongIcon fontSize="small" sx={REPLENISHMENT_FIELD_ICON_SX} />}
                title={t("DO Code Last 4")}
                required
              >
                <ReplenishmentTextField
                  value={doCodeSuffix}
                  onChange={(e) => {
                    setDoCodeSuffix(e.target.value.slice(0, 4));
                    setSourceDo(null);
                  }}
                  placeholder={t("replenishmentDoSuffixPlaceholder")}
                  inputProps={{ maxLength: 4 }}
                  onKeyDown={(e) => {
                    if (e.key === "Enter") {
                      e.preventDefault();
                      void handleLookupSourceDo();
                    }
                  }}
                />
              </ReplenishmentFilterField>

              <Box
                sx={{
                  gridColumn: { xs: "1", sm: "1 / -1", lg: "auto" },
                  minWidth: 0,
                }}
              >
                <ReplenishmentFilterField
                  icon={<StorefrontIcon fontSize="small" sx={REPLENISHMENT_FIELD_ICON_SX} />}
                  title={t("Shop Code")}
                  required
                >
                  <ReplenishmentTextField
                    value={shopInput}
                    onChange={(e) => {
                      setShopInput(e.target.value);
                      setSourceDo(null);
                    }}
                    placeholder={t("replenishmentShopPlaceholder")}
                    onKeyDown={(e) => {
                      if (e.key === "Enter") {
                        e.preventDefault();
                        void handleLookupSourceDo();
                      }
                    }}
                  />
                </ReplenishmentFilterField>
              </Box>
            </Box>

            <Stack
              direction={{ xs: "column", sm: "row" }}
              spacing={1.5}
              useFlexGap
              flexWrap="wrap"
            >
              <Button
                variant="contained"
                disableElevation
                onClick={() => void handleLookupSourceDo()}
                disabled={isLookingUp}
                sx={REPLENISHMENT_LOOKUP_BUTTON_SX}
              >
                {t("Lookup")}
              </Button>
              <Button
                variant="outlined"
                disableElevation
                startIcon={<InfoOutlinedIcon fontSize="small" />}
                onClick={() => setTrackingDialogOpen(true)}
                sx={REPLENISHMENT_OUTLINED_ACTION_BUTTON_SX}
              >
                {t("Replenishment Tracking")}
              </Button>
            </Stack>
          </Stack>

          {sourceDo && (
            <Box sx={REPLENISHMENT_SOURCE_HEADER_SX}>
              <Stack spacing={0.5} sx={{ width: "100%" }}>
                <Typography
                  variant="body2"
                  fontWeight={700}
                  sx={{ wordBreak: "break-word", lineHeight: 1.5 }}
                >
                  {t("Delivery Order Code")}: {sourceDo.doCode}
                  {"　"}
                  {t("Shop Name")}: {sourceDo.shopName ?? "—"}
                </Typography>
                <Typography
                  variant="body2"
                  fontWeight={700}
                  sx={{ wordBreak: "break-word", lineHeight: 1.5 }}
                >
                  {t("Truck Lane")}:{" "}
                  {sourceDo.truckLaneCode?.trim() ? sourceDo.truckLaneCode : t("Truck X")}
                </Typography>
              </Stack>
            </Box>
          )}


          {sourceDo && (
            <Stack spacing={1.5}>
              <Box
                sx={(theme) => ({
                  border: `1px solid ${theme.palette.divider}`,
                  borderRadius: 2,
                  p: 1.5,
                  bgcolor: theme.palette.mode === "dark" ? "grey.900" : "common.white",
                })}
              >
                <Stack spacing={1.5}>
                  <Box
                    sx={{
                      display: "grid",
                      gridTemplateColumns: "minmax(0, 3fr) minmax(0, 7fr)",
                      gap: 1.5,
                      alignItems: "start",
                    }}
                  >
                    <ReplenishmentFilterField
                      icon={<ReceiptLongIcon fontSize="small" sx={REPLENISHMENT_FIELD_ICON_SX} />}
                      title={t("Replenishment item code")}
                      required
                    >
                      <Autocomplete
                        size="small"
                        fullWidth
                        options={sourceDo.lines}
                        value={selectedLine}
                        onChange={(_, newValue) => setSelectedLine(newValue)}
                        onInputChange={(_, inputValue, reason) => {
                          if (reason === "clear") {
                            setSelectedLine(null);
                            return;
                          }
                          if (reason === "input" && selectedLine) {
                            const selectedCode = (selectedLine.itemNo ?? "").trim();
                            if (inputValue.trim() !== selectedCode) {
                              setSelectedLine(null);
                            }
                          }
                        }}
                        getOptionLabel={(line) => line.itemNo ?? ""}
                        isOptionEqualToValue={(a, b) => a.id === b.id}
                        filterOptions={(options, { inputValue }) =>
                          filterSourceDoLinesByItemNo(options, inputValue)
                        }
                        renderInput={(params) => {
                          const { inputProps } = params;
                          return (
                            <ReplenishmentTextField
                              {...params}
                              placeholder={t("Replenishment item code")}
                              inputProps={{
                                ...inputProps,
                                ref: (node: HTMLInputElement | null) => {
                                  itemCodeInputRef.current = node;
                                  const { ref } = inputProps;
                                  if (typeof ref === "function") ref(node);
                                  else if (ref) {
                                    (
                                      ref as React.MutableRefObject<HTMLInputElement | null>
                                    ).current = node;
                                  }
                                },
                              }}
                              InputProps={{ ...params.InputProps, disableUnderline: true }}
                            />
                          );
                        }}
                        sx={REPLENISHMENT_AUTOCOMPLETE_SX}
                      />
                    </ReplenishmentFilterField>

                    <ReplenishmentFilterField title={t("Item Name")}>
                      <Autocomplete
                        size="small"
                        fullWidth
                        options={sourceDo.lines}
                        value={selectedLine}
                        onChange={(_, newValue) => setSelectedLine(newValue)}
                        onInputChange={(_, inputValue, reason) => {
                          if (reason === "clear") {
                            setSelectedLine(null);
                            return;
                          }
                          if (reason === "input" && selectedLine) {
                            const selectedName = sourceDoLineNameLabel(selectedLine);
                            if (inputValue.trim() !== selectedName) {
                              setSelectedLine(null);
                            }
                          }
                        }}
                        getOptionLabel={sourceDoLineNameLabel}
                        isOptionEqualToValue={(a, b) => a.id === b.id}
                        filterOptions={(options, { inputValue }) =>
                          filterSourceDoLinesByItemName(options, inputValue)
                        }
                        renderInput={(params) => (
                          <ReplenishmentTextField
                            {...params}
                            placeholder={t("Replenishment item name")}
                            InputProps={{ ...params.InputProps, disableUnderline: true }}
                          />
                        )}
                        sx={REPLENISHMENT_AUTOCOMPLETE_SX}
                      />
                    </ReplenishmentFilterField>
                  </Box>

                  <Box
                    sx={{
                      display: "grid",
                      gridTemplateColumns: {
                        xs: "1fr",
                        sm: "repeat(2, minmax(0, 1fr))",
                        md: "minmax(0, 1fr) minmax(0, 1fr) minmax(0, 1.2fr) auto",
                      },
                      gap: 1.5,
                      alignItems: "start",
                    }}
                  >
                    <ReplenishmentFilterField title={t("Original Shipment Qty")}>
                      <ReplenishmentReadonlyValue fontWeight={600}>
                        {selectedLine
                          ? `${resolveOriginalShipmentQty(selectedLine)}${selectedLineUom ? ` ${selectedLineUom}` : ""}`
                          : null}
                      </ReplenishmentReadonlyValue>
                    </ReplenishmentFilterField>

                    <ReplenishmentFilterField title={t("Replenish Qty")} required>
                      <ReplenishmentTextField
                        type="number"
                        value={replenishQtyInput}
                        onChange={(e) => setReplenishQtyInput(e.target.value)}
                        placeholder={t("Replenish Qty")}
                        disabled={!selectedLine}
                        inputProps={{ min: 0, step: "any" }}
                        onKeyDown={(e) => {
                          if (e.key === "Enter") {
                            e.preventDefault();
                            handleAddDraftRow();
                          }
                        }}
                      />
                    </ReplenishmentFilterField>

                    <ReplenishmentFilterField title={t("Remark")}>
                      <FormControl
                        fullWidth
                        size="small"
                        variant="filled"
                        hiddenLabel
                        disabled={!selectedLine}
                        sx={REPLENISHMENT_FILLED_SELECT_SX}
                      >
                        <Select
                          value={replenishReasonInput}
                          onChange={(e) =>
                            setReplenishReasonInput(
                              e.target.value as ReplenishmentReasonCode | "",
                            )
                          }
                          displayEmpty
                          disableUnderline
                          renderValue={(selected) => {
                            if (!selected) {
                              return (
                                <Typography
                                  component="span"
                                  variant="body2"
                                  color="text.secondary"
                                  sx={{ fontWeight: 400 }}
                                >
                                  {t("replenishmentRemarkPlaceholder")}
                                </Typography>
                              );
                            }
                            return t(`replenishmentReason.${selected}`);
                          }}
                        >
                          <MenuItem value="">
                            <em>{t("replenishmentRemarkPlaceholder")}</em>
                          </MenuItem>
                          {REPLENISHMENT_REASON_CODES.map((code) => (
                            <MenuItem key={code} value={code}>
                              {t(`replenishmentReason.${code}`)}
                            </MenuItem>
                          ))}
                        </Select>
                      </FormControl>
                    </ReplenishmentFilterField>

                    <Stack
                      spacing={1}
                      sx={{
                        minWidth: 0,
                        gridColumn: { xs: "1", sm: "1 / -1", md: "auto" },
                      }}
                    >
                      <ReplenishmentFieldLabelSpacer />
                      <Button
                        variant="outlined"
                        startIcon={<Add />}
                        onClick={handleAddDraftRow}
                        disabled={!selectedLine}
                        sx={REPLENISHMENT_OUTLINED_ACTION_BUTTON_SX}
                      >
                        {t("Add Row")}
                      </Button>
                    </Stack>
                  </Box>
                </Stack>
              </Box>

              {currentDoDraftRows.length > 0 ? (
                <Typography variant="caption" color="text.secondary">
                  {t("replenishmentCurrentDoDraftHint", { count: currentDoDraftRows.length })}
                </Typography>
              ) : null}
            </Stack>
          )}
          </Stack>
        </Paper>

        <Box sx={{ display: { xs: "none", xl: "block" }, minHeight: 0 }}>
          {draftPreviewPanel}
        </Box>
      </Box>

      <Box sx={{ display: { xs: "block", xl: "none" } }}>{draftPreviewPanel}</Box>

      <Dialog
        open={trackingDialogOpen}
        onClose={() => setTrackingDialogOpen(false)}
        maxWidth="lg"
        fullWidth
      >
        <DialogTitle
          sx={{
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
            pr: 1,
          }}
        >
          {t("Replenishment Tracking")}
          <IconButton
            size="small"
            onClick={() => setTrackingDialogOpen(false)}
            aria-label={t("Cancel")}
          >
            <Close fontSize="small" />
          </IconButton>
        </DialogTitle>
        <DialogContent
          sx={{
            p: 2,
            bgcolor: (theme) => (theme.palette.mode === "dark" ? "grey.900" : "grey.50"),
          }}
        >
          <Stack spacing={2}>
            <Box
              sx={{
                display: "grid",
                gridTemplateColumns: { xs: "1fr", sm: "1fr 1fr" },
                gap: 2,
              }}
            >
              <ReplenishmentFilterField
                icon={<CalendarTodayIcon fontSize="small" sx={REPLENISHMENT_FIELD_ICON_SX} />}
                title={t("replenishmentTargetDoEstimatedArrivalDate")}
              >
                <LocalizationProvider dateAdapter={AdapterDayjs}>
                  <DatePicker
                    format="YYYY-MM-DD"
                    value={trackDateFilter}
                    onChange={(v) => {
                      setTrackDateFilter(v);
                      setTrackPage(0);
                    }}
                    slotProps={datePickerSlotProps}
                    sx={{ width: "100%" }}
                  />
                </LocalizationProvider>
              </ReplenishmentFilterField>
              <ReplenishmentFilterField
                icon={<FilterListIcon fontSize="small" sx={REPLENISHMENT_FIELD_ICON_SX} />}
                title={t("Status")}
              >
                <FormControl
                  fullWidth
                  size="small"
                  variant="filled"
                  hiddenLabel
                  sx={REPLENISHMENT_FILLED_SELECT_SX}
                >
                  <Select
                    value={trackStatusFilter}
                    onChange={(e) => {
                      setTrackStatusFilter(e.target.value as ReplenishmentStatus | "all");
                      setTrackPage(0);
                    }}
                    disableUnderline
                  >
                    <MenuItem value="all">{t("All")}</MenuItem>
                    <MenuItem value="pending">{t("pending")}</MenuItem>
                    <MenuItem value="processing">{t("processing")}</MenuItem>
                    <MenuItem value="completed">{t("completed")}</MenuItem>
                  </Select>
                </FormControl>
              </ReplenishmentFilterField>
            </Box>

            <Paper
              variant="outlined"
              sx={(theme) => ({
                borderRadius: 2,
                bgcolor: theme.palette.mode === "dark" ? "grey.900" : "common.white",
                opacity: isLoadingTracking ? 0.6 : 1,
                pointerEvents: isLoadingTracking ? "none" : "auto",
                display: "flex",
                flexDirection: "column",
                maxHeight: "65vh",
              })}
            >
              <Stack
                spacing={1.5}
                sx={{
                  p: 1.5,
                  flex: 1,
                  minHeight: 0,
                  overflowY: "auto",
                  "& > *": { flexShrink: 0 },
                }}
              >
                {paginatedTrackRecords.length === 0 ? (
                  <Typography align="center" color="text.secondary" sx={{ py: 4 }}>
                    {isLoadingTracking ? t("Loading") : t("No data")}
                  </Typography>
                ) : (
                  paginatedTrackRecords.map((row) => (
                    <Paper
                      key={row.id}
                      variant="outlined"
                      sx={(theme) => ({
                        p: 2,
                        borderRadius: 1.5,
                        flexShrink: 0,
                        overflow: "visible",
                        bgcolor:
                          theme.palette.mode === "dark" ? "grey.800" : "grey.50",
                      })}
                    >
                      <Box
                        sx={{
                          display: "grid",
                          gridTemplateColumns: { xs: "1fr", md: "1fr 1fr 1fr" },
                          gap: { xs: 2, md: 3 },
                          alignItems: "start",
                          minWidth: 0,
                        }}
                      >
                        <Stack spacing={1.25}>
                          <TrackingFieldBlock
                            label={t("Truck Lance Code")}
                            value={row.truckLaneCode ?? "—"}
                          />
                          <TrackingFieldBlock
                            label={t("Shop Name")}
                            value={row.shopName ?? "—"}
                          />
                          <TrackingFieldBlock
                            label={t("replenishmentOriginalSourceDoCode")}
                            value={row.sourceDoCode || "—"}
                          />
                        </Stack>

                        <Stack spacing={1}>
                          <TrackingFieldBlock label={t("Replenishment Code")} value={row.code} />
                          <TrackingFieldBlock
                            label={t("replenishmentItemInfo")}
                            value={`${row.itemNo} ${row.itemName}`.trim() || "—"}
                          />
                          <TrackingInlineLine label={t("Original Shipment Qty")}>
                            {formatQtyWithUom(row.originalQty, row.shortUom)}
                          </TrackingInlineLine>
                          <TrackingInlineLine label={t("Replenish Qty")}>
                            {formatQtyWithUom(row.replenishQty, row.shortUom)}
                          </TrackingInlineLine>
                          <TrackingInlineLine label={t("Remark")}>
                            {formatReplenishmentReason(row.reason, t)}
                          </TrackingInlineLine>
                        </Stack>

                        <Stack spacing={1.25}>
                          <TrackingFieldBlock
                            label={t("replenishmentTargetDoCode")}
                            value={row.targetDoCode ?? "—"}
                          />
                          <TrackingFieldBlock
                            label={t("replenishmentTargetDoEstimatedArrivalDate")}
                            value={
                              row.targetDoEstimatedArrivalDate
                                ? dayjs(row.targetDoEstimatedArrivalDate).format("YYYY-MM-DD")
                                : "—"
                            }
                          />
                          <TrackingFieldBlock
                            label={t("replenishmentRelateTicketNo")}
                            value={row.relateTicketNo ?? "—"}
                          />
                          <TrackingInlineLine label={t("replenishmentActualPickQty")}>
                            {formatQtyWithUom(row.actualPickQty, row.shortUom)}
                          </TrackingInlineLine>
                          <TrackingFieldBlock
                            label={t("replenishmentStatusLabel")}
                            value={t(row.status)}
                          />
                        </Stack>
                      </Box>
                    </Paper>
                  ))
                )}
              </Stack>
              <TablePagination
                component="div"
                count={records.length}
                page={trackPage}
                onPageChange={(_, page) => setTrackPage(page)}
                rowsPerPage={trackRowsPerPage}
                onRowsPerPageChange={(e) => {
                  setTrackRowsPerPage(Number(e.target.value));
                  setTrackPage(0);
                }}
                rowsPerPageOptions={[10, 25, 50]}
                labelRowsPerPage={t("Rows per page")}
                sx={{ flexShrink: 0, borderTop: 1, borderColor: "divider" }}
              />
            </Paper>
          </Stack>
        </DialogContent>
      </Dialog>
    </Stack>
  );
};

export default DoReplenishmentTab;
