import { Typography } from '@mui/material';
import { styled } from '@mui/material/styles';
import { get } from 'lodash';
import { useRecordContext, useTranslate } from 'ra-core';

const Root = styled('div', { overridesResolver: (_, styles) => styles.root })({ display: 'inline-block' });

const StyledList = styled('ul')({
  display: 'inline-block'
});

function BaseAttachmentField(props: BaseAttachmentFieldProps): JSX.Element | any {
  const { className, emptyText, source, title, ...rest } = props;
  const record = useRecordContext(props);
  const sourceValue = get(record, source);
  const translate = useTranslate();

  if (!sourceValue) {
    return emptyText ? (
      <Typography component="span" variant="body2" className={className} {...rest}>
        {emptyText ? translate(emptyText, { _: emptyText }) : null}
      </Typography>
    ) : (
      <Root className={className} {...rest} />
    );
  }

  if (Array.isArray(sourceValue)) {
    return (
      <StyledList className={className} {...rest}>
        {sourceValue.map((file, index) => {
          const fileTitleValue = title instanceof String ? get(file, title as string)?.toString() : title;
          return <li key={index}>{fileTitleValue}</li>;
        })}
      </StyledList>
    );
  }

  const titleValue = title instanceof String ? get(record, title as string)?.toString() : title;

  return (
    <Root className={className} {...rest}>
      {titleValue}
    </Root>
  );
}

type BaseAttachmentFieldProps = {
  src: string;
  title: string | ((record: any) => string) | JSX.Element;
  target: string;
  download: boolean | string;
  ping: string;
  rel: string;
  emptyText: string;
  source: string;
  className: string;
  disabled?: boolean;
  record: any;
  onClick: (e: any) => void;
};

export { BaseAttachmentField };
export type { BaseAttachmentFieldProps };
