import type { FC } from 'react';
import React from 'react';
import { TruncatedText } from '@theorchard/suite-components';
import { formatMessage } from '@theorchard/suite-frontend';
import { EMPTY_CHAR } from 'src/constants';

const CLASSNAME = 'DataList';
const CLASSNAME_ITEM = 'DataListItem';
const CLASSNAME_ITEM_LABEL = 'DataListItemLabel';
const CLASSNAME_ITEM_VALUE = 'DataListItemValue';

export const TEST_ID = CLASSNAME;

interface Props {
    children: React.ReactNode;
}

interface ItemProps {
    label: string;
    value?: string | JSX.Element;
    maxLength?: number;
}

const DataListItem: FC<ItemProps> = ({ label, value, maxLength }) => (
    <div className={CLASSNAME_ITEM}>
        <span className={CLASSNAME_ITEM_LABEL}>{formatMessage(label)}:</span>
        <span className={CLASSNAME_ITEM_VALUE}>
            {maxLength && typeof value === 'string' && (
                <TruncatedText text={value} maxWidth={maxLength} />
            )}
            {!maxLength && (value ?? EMPTY_CHAR)}
        </span>
    </div>
);

type DataListType = FC<Props> & { Item: typeof DataListItem };

const DataList: DataListType = ({ children }) => (
    <div className={CLASSNAME} data-testid={TEST_ID}>
        {children}
    </div>
);

DataList.Item = DataListItem;

export default DataList;
