import { memo } from 'react';
import type { ReactNode } from 'react';

import Box from '@mui/material/Box';
import Card from '@mui/material/Card';
import Typography from '@mui/material/Typography';

import { Avatar } from '../../avatar';
import type { AvatarProps } from '../../avatar';
import { CustomIcon } from '../../custom-icon';
import type { CustomIconProps } from '../../custom-icon';
import { TextWithTooltip } from '../../text-with-tooltip';

import clsx from 'clsx';
import map from 'lodash/map';
import createClasses from './styles';

export interface DictionaryCardProps {
  /**
   * Title of the component.
   */
  title: string | ReactNode;
  /**
   * Props which will be passed into the avatar component.
   */
  avatarProps?: AvatarProps;
  /**
   * Main icon to be placed instead of the avatar (avatarProps will be ignored).
   */
  mainIcon?: CustomIconProps;
  /**
   * Items which keys and value will be displayed.
   */
  items: Record<string, ReactNode>;
  /**
   * To override default classes.
   */
  classes?: Partial<ReturnType<typeof createClasses>>;
}

const DictionaryCard = (props: DictionaryCardProps) => {
  const { avatarProps, mainIcon, title, items, classes } = props;

  const styles = createClasses();

  return (
    <Card className={clsx(styles.root, classes?.root)}>
      <Box display="flex" alignItems="center">
        {mainIcon?.src ? (
          <CustomIcon size="large" className={styles.mainIcon} {...mainIcon} />
        ) : (
          avatarProps && <Avatar size="medium" {...avatarProps} />
        )}
        <Typography
          component="div"
          className={clsx(
            styles.title,
            (avatarProps || mainIcon) && styles.titleWithAvatar,
            (avatarProps || mainIcon) && classes?.titleWithAvatar
          )}
        >
          {title}
        </Typography>
      </Box>
      <Box
        display="flex"
        flexDirection="column"
        ml={avatarProps ? 6 : undefined}
        component="ul"
        className={styles.cardItems}
      >
        {map(items, (value, key) => (
          <Box
            key={key}
            component="li"
            display="flex"
            justifyContent="space-between"
            alignItems="baseline"
            className={styles.cardItem}
          >
            <TextWithTooltip
              numOfLines={1}
              text={`${key}:`}
              classes={{
                text: clsx(styles.key, classes?.key)
              }}
            />
            <Typography className={clsx(styles.value, classes?.value)}>{value}</Typography>
          </Box>
        ))}
      </Box>
    </Card>
  );
};

DictionaryCard.defaultProps = {};

const m = memo(DictionaryCard);
export { m as DictionaryCard };
