'use client';
import { fetchItemUomConversions, ItemUomConversionRow } from '@/app/api/inventory/actions';
import { InventoryResult } from '@/app/api/inventory';
import { useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
Box,
Checkbox,
CircularProgress,
Paper,
Table,
TableBody,
TableCell,
TableContainer,
TableHead,
TableRow,
Typography,
} from '@mui/material';
interface Props {
inventory: InventoryResult | null;
}
const formatRatio = (value: number) => {
if (!Number.isFinite(value)) return '';
return String(value);
};
const cellSx = {
px: 1.25,
py: 0.75,
fontSize: 13,
lineHeight: 1.4,
} as const;
const numSx = {
...cellSx,
width: '9%',
whiteSpace: 'nowrap',
fontVariantNumeric: 'tabular-nums',
} as const;
const flagSx = {
...cellSx,
width: '8%',
textAlign: 'center',
} as const;
const FlagCell = ({ checked }: { checked: boolean }) => (
);
const InventoryItemUom: React.FC = ({ inventory }) => {
const { t } = useTranslation('inventory');
const [rows, setRows] = useState([]);
const [loading, setLoading] = useState(false);
const requestRef = useRef(0);
const itemId = inventory?.itemId;
useEffect(() => {
if (itemId == null) {
setRows([]);
setLoading(false);
return;
}
const requestId = ++requestRef.current;
setLoading(true);
fetchItemUomConversions(itemId)
.then((res) => {
if (requestId !== requestRef.current) return;
setRows(res ?? []);
})
.catch((error) => {
if (requestId !== requestRef.current) return;
console.error('Failed to load item unit conversions:', error);
setRows([]);
})
.finally(() => {
if (requestId === requestRef.current) setLoading(false);
});
}, [itemId]);
if (!inventory || itemId == null) {
return {t('No items are selected yet.')};
}
const flags = [
t('Base Unit'),
t('Stock Unit'),
t('Picking Unit'),
t('Sales Unit'),
t('Purchase Unit'),
t('Inactive'),
];
return (
{`${t('Item selected')}: ${inventory.itemCode} | ${inventory.itemName} (${t(inventory.itemType)})`}
{loading ? (
) : (
{t('Unit')}
{t('Unit Description')}
{t('Ratio Numerator')}
{t('Ratio Denominator')}
{flags.map((label) => (
{label}
))}
{rows.length === 0 ? (
{t('No data')}
) : (
rows.map((row) => (
{row.unitCode}
{row.unitDesc}
{formatRatio(row.ratioN)}
{formatRatio(row.ratioD)}
))
)}
)}
);
};
export default InventoryItemUom;