import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import { Box, Button, Typography } from '@mui/material';
import isEmpty from 'lodash/isEmpty';
import isObject from 'lodash/isObject';

import { isObjectContent } from '../../libs/util';
import InfoRow from '../info-row';

export default function MetadataList({
  data,
  handleEditMetadata = () => {},
}: {
  data: any;
  handleEditMetadata?: () => void;
}) {
  const { t } = useLocaleContext();

  if (isEmpty(data)) {
    return (
      <Box sx={{ textAlign: 'center' }}>
        <Typography
          variant="subtitle1"
          sx={{
            color: 'text.primary',
            fontWeight: 500,
          }}>
          {t('common.metadata.empty')}
        </Typography>
        <Typography
          variant="body2"
          sx={{
            color: 'text.lighter',
          }}>
          {t('common.metadata.emptyTip')}
        </Typography>
        <Button sx={{ color: 'text.link' }} onClick={handleEditMetadata}>
          {t('common.add')}
        </Button>
      </Box>
    );
  }

  const formatValue = (value: any) => {
    if (isObjectContent(value)) {
      return <pre style={{ whiteSpace: 'break-spaces' }}>{JSON.stringify(JSON.parse(value), null, 2)}</pre>;
    }
    if (isObject(value)) {
      return <pre style={{ whiteSpace: 'break-spaces' }}>{JSON.stringify(value, null, 2)}</pre>;
    }
    if (typeof value === 'boolean') {
      return String(value);
    }
    return value;
  };

  // skip non-string values
  return (
    <>
      {Object.keys(data || {}).map((key) => (
        <InfoRow key={key} label={key} value={formatValue(data[key])} direction="column" alignItems="flex-start" />
      ))}
    </>
  );
}
