import { styled } from '@mui/material/styles';
import { get } from 'lodash';
import { useCallback } from 'react';
import { FileField as RaFileField, FileFieldProps as RaFileFieldProps, useRecordContext } from 'react-admin';

type FileFieldProps = {
  source: string;
  title: string;
} & RaFileFieldProps;

const StyledFileField = styled(RaFileField, { slot: 'root' })(() => ({}));

/**
 * This component works with Base64 files.
 */
function FileField({ ...props }: FileFieldProps): JSX.Element {
  const record = useRecordContext(props);
  const handleClick = useCallback(
    (event: Event) => {
      event.preventDefault();
      event.stopPropagation();
      const base64 = get(record, `_${props?.source}`, get(record, props?.source));
      const name = get(record, props?.title || props?.source) || props?.title;
      const link = document.createElement('a');
      link.href = base64;
      link.download = name;
      link.click();
    },
    [props?.source, record, props?.title]
  );
  return (
    <StyledFileField
      {...props}
      record={record}
      // @ts-ignore
      onClick={handleClick}
    />
  );
}

export { FileField };
export type { FileFieldProps };
