import { Typography } from '@mui/material';
import { get } from 'lodash';
import { FieldProps, useRecordContext } from 'react-admin';

function SizeField({ source, ...props }: SizeFieldProps): JSX.Element {
  const record = useRecordContext(props);
  const size = get(record, source, 0);
  const sizeInKb = size / 1024;
  const sizeInMb = sizeInKb / 1024;
  const sizeInGb = sizeInMb / 1024;

  const value =
    sizeInGb > 1
      ? `${sizeInGb.toFixed(2)} GB`
      : sizeInMb > 1
      ? `${sizeInMb.toFixed(2)} MB`
      : sizeInKb > 1
      ? `${sizeInKb.toFixed(2)} KB`
      : `${size.toFixed(2)} B`;
  return (
    <Typography component="span" variant="body1" {...props}>
      {value}
    </Typography>
  );
}

type SizeFieldProps = {
  source: string;
} & FieldProps;

export { SizeField };
export type { SizeFieldProps };
