"use client";

import type { PoWorkbenchReceivedQtyTone } from "@/components/PoWorkbench/detailsGrid/poWorkbenchReceivedQtyTone";
import Box from "@mui/material/Box";
import Stack from "@mui/material/Stack";
import Typography from "@mui/material/Typography";
import type { SxProps, Theme } from "@mui/material/styles";

/** Shared row height so qty digits align across expected / received columns. */
export const DETAILS_GRID_QTY_VALUE_ROW_MIN_HEIGHT = "1.65rem";

export const DETAILS_GRID_QTY_VALUE_FONT_SIZE = "1.375rem";

const QTY_VALUE_ROW_SX = {
  minHeight: DETAILS_GRID_QTY_VALUE_ROW_MIN_HEIGHT,
  display: "flex",
  alignItems: "center",
  justifyContent: "center",
  width: "100%",
} as const;

const QTY_VALUE_SX = {
  fontSize: DETAILS_GRID_QTY_VALUE_FONT_SIZE,
  fontWeight: 700,
  lineHeight: 1.2,
  textAlign: "center",
  color: "text.primary",
  fontVariantNumeric: "tabular-nums",
} as const;

function qtyValueColorSx(
  tone?: PoWorkbenchReceivedQtyTone,
): SxProps<Theme> {
  if (!tone) return {};
  if (tone === "complete") return { color: "success.main" };
  if (tone === "variance") return { color: "warning.main" };
  return { color: "error.main" };
}

const UNIT_BADGE_SX = (theme: import("@mui/material/styles").Theme) => ({
  width: "100%",
  maxWidth: "100%",
  minWidth: 0,
  px: 0.875,
  py: 0.625,
  borderRadius: 0.75,
  textAlign: "center",
  bgcolor: theme.palette.mode === "dark" ? "grey.800" : "grey.100",
  border: 1,
  borderColor: "divider",
});

const UNIT_LABEL_WRAP_SX = {
  display: "flex",
  flexWrap: "wrap",
  justifyContent: "center",
  alignItems: "center",
  columnGap: 0,
  rowGap: 0.25,
  width: "100%",
  minWidth: 0,
} as const;

const UNIT_SEGMENT_SX = {
  fontSize: "0.8125rem",
  lineHeight: 1.4,
  color: "text.primary",
  whiteSpace: "nowrap",
} as const;

const UNIT_LABEL_PLAIN_SX = {
  ...UNIT_SEGMENT_SX,
  whiteSpace: "normal",
  textAlign: "center",
  overflowWrap: "break-word",
  wordBreak: "break-word",
  width: "100%",
} as const;

/** Split at `X` / `×` so tiers stay together (e.g. `150克`, `100包`). */
function splitPurchaseUnitLabel(label: string): string[] {
  return label.split(/X|×/i).filter((part) => part.length > 0);
}

function UnitLabelContent({ unitLabel }: { unitLabel: string }) {
  const segments = splitPurchaseUnitLabel(unitLabel);

  if (segments.length <= 1) {
    return (
      <Typography component="div" sx={UNIT_LABEL_PLAIN_SX}>
        {unitLabel}
      </Typography>
    );
  }

  return (
    <Box sx={UNIT_LABEL_WRAP_SX}>
      {segments.map((segment, index) => (
        <Typography key={index} component="span" sx={UNIT_SEGMENT_SX}>
          {index === 0 ? segment : `X${segment}`}
        </Typography>
      ))}
    </Box>
  );
}

function formatQty(qty: number): string {
  return qty.toLocaleString();
}

export interface PoWorkbenchDetailsGridQtyUnitBlockProps {
  qty: number;
  unitLabel: string;
  /** Purchase-side qty color in received column (green = met/over, yellow = under, red = none). */
  purchaseQtyTone?: PoWorkbenchReceivedQtyTone;
}

/** Centered qty with purchase / inventory unit badge below. */
export default function PoWorkbenchDetailsGridQtyUnitBlock({
  qty,
  unitLabel,
  purchaseQtyTone,
}: PoWorkbenchDetailsGridQtyUnitBlockProps) {
  return (
    <Stack
      alignItems="stretch"
      justifyContent="center"
      spacing={0.5}
      sx={{ width: "100%", minWidth: 0 }}
    >
      <Box sx={QTY_VALUE_ROW_SX}>
        <Typography sx={{ ...QTY_VALUE_SX, ...qtyValueColorSx(purchaseQtyTone) }}>
          {formatQty(qty)}
        </Typography>
      </Box>
      <Box sx={UNIT_BADGE_SX}>
        <UnitLabelContent unitLabel={unitLabel} />
      </Box>
    </Stack>
  );
}
