import { ImageAttachmentField, ImageAttachmentFieldProps } from '@/components/ra-fields';
import _ from 'lodash';
import { RecordContextProvider, useRecordContext } from 'ra-core';
import { ImageField } from 'ra-ui-materialui';
import { useEffect, useState } from 'react';
import { AttachmentInput, AttachmentInputProps } from './AttachmentInput';

type ImageAttachmentInputProps = Omit<AttachmentInputProps, 'children'>;

function ImageAttachmentInput(props: ImageAttachmentInputProps) {
  const { source } = props;
  const record = useRecordContext(props);
  const { id: entityId } = record ?? {};

  return (
    <AttachmentInput {...props}>
      <Field entityId={String(entityId)} source={source} />
    </AttachmentInput>
  );
}

function Field(props: { entityId?: string; source?: string }) {
  const value = useRecordContext();

  return _.isNil(value?.rawFile) ? (
    <AttachmentPreview {...props} />
  ) : (
    <ImageField {...props} title="title" source={'src'} />
  );
}

function AttachmentPreview(props: ImageAttachmentFieldProps & { entityId?: string }) {
  const { entityId, ...rest } = props;
  const source = props.source ?? '';
  const value = useRecordContext();
  const [context, setContext] = useState(source ? { id: entityId, [source]: value } : { id: entityId });

  useEffect(() => {
    setContext({ id: entityId, [source]: value });
  }, [value, entityId, source]);

  return (
    <RecordContextProvider value={context}>
      <ImageAttachmentField {...rest} />
    </RecordContextProvider>
  );
}

export { ImageAttachmentInput };
