import React, { memo, useMemo } from "react";

import { Box, Stack, Typography } from "@mui/material";

export interface LabeledValueProps {
  label: string;
  value: string | React.ReactNode;
  compact?: boolean;
  multiline?: boolean;
}

export const LabeledValue: React.FC<LabeledValueProps> = ({ label, value, compact, multiline }) => {
  // Use thinner font if compact and value is > 20 chars.
  const xsFont = useMemo(
    () =>
      value != null && typeof value === "string" && value.length > 20 ? '"wdth" 75' : '"wdth" 100',
    [value],
  );

  return (
    <Stack
      direction={compact ? "row" : "column"}
      justifyContent={compact ? "space-between" : "flex-start"}
    >
      <Typography
        color="text.secondary"
        fontWeight={500}
        sx={{ whiteSpace: "nowrap", fontVariationSettings: { sm: '"wdth" 100', xs: '"wdth" 75' } }}
        variant="subtitle2"
      >
        {label}
      </Typography>

      {typeof value === "string" ? (
        <Typography
          sx={{
            whiteSpace: multiline ? "break-spaces" : "pre-wrap",
            wordBreak: "break-all",
            fontVariationSettings: { sm: xsFont, xs: '"wdth" 75' },
          }}
          variant={compact ? "body2" : "body1"}
        >
          {value}
        </Typography>
      ) : (
        <Box>{value}</Box>
      )}
    </Stack>
  );
};

export default memo(LabeledValue);
