import _ from 'lodash';
import { useEffect, useState } from 'react';
import { FieldProps, ImageField, useDataProvider, useRecordContext, useResourceContext } from 'react-admin';

type ImageAttachmentFieldProps<RecordType extends Record<string, any> = Record<string, any>> = FieldProps<RecordType>;
type ContextValueImage = { url: string; title?: string };

function ImageAttachmentField(props: ImageAttachmentFieldProps) {
  const { resource: propResource, source } = props;
  const dataProvider = useDataProvider();
  const defaultResource = useResourceContext();
  const entity = !_.isNil(propResource) ? propResource : defaultResource?.match(/(?<=\/)[^\/]+$/)?.[0]; //eslint-disable-line
  const recordContext = useRecordContext(props);
  const entityId = recordContext?.id;
  const attachment = recordContext?.[source ?? ''];
  const [nestedContextValue, setNestedContextValue] = useState<{
    image: ContextValueImage | Array<ContextValueImage>;
  } | null>(null);

  useEffect(() => {
    if (_.isNil(attachment) || _.isNil(dataProvider) || _.isNil(entity) || _.isNil(entityId) || _.isNil(source)) {
      return;
    }
    const basePath = `/attachments/${entity}/${entityId}/${source}/`;
    function getAttachment(attachment: { id: string; name: string }): Promise<ContextValueImage> {
      return dataProvider
        .getFile(`${basePath}${attachment?.id}`)
        .then((url: string) => ({ url, title: attachment?.name }));
    }

    if (_.isArray(attachment)) {
      Promise.all(attachment.map(getAttachment)).then((images: Array<ContextValueImage>) => {
        setNestedContextValue({ image: images });
      });
    } else {
      getAttachment(attachment).then((image: ContextValueImage) => {
        setNestedContextValue({ image });
      });
    }
  }, [attachment, dataProvider, entity, entityId, source]);

  if (_.isNil(nestedContextValue)) {
    return null;
  }

  return (
    <ImageField
      {...props}
      src="url"
      source={_.isArray(attachment) ? 'image' : 'image.url'}
      title="image.title"
      record={nestedContextValue}
    />
  );
}

export { ImageAttachmentField };
export type { ImageAttachmentFieldProps };
