import { CoverField } from '@/components/ra-fields';
import { LabeledInput } from '@/components/ra-inputs/LabeledInput';
import { get } from 'lodash';
import React from 'react';
import {
  ImageInput as RaImageInput,
  ImageInputProps as RaImageInputProps,
  useInput,
  useRecordContext
} from 'react-admin';
import { useWatch } from 'react-hook-form';

type ImageInputProps = {
  source: string;
  title?: string;
  children?: React.ReactNode;
  multiple?: boolean;
} & RaImageInputProps;

function ImageInput({ children = <CoverField />, title, multiple = false, ...props }: ImageInputProps): JSX.Element {
  const file = useWatch({ name: props.source });
  const record = useRecordContext(props);
  const { source } = props;
  useInput({ source: `__image__${props?.source}`, defaultValue: props?.source });
  return (
    // @ts-ignore
    <LabeledInput {...props} multiple={multiple}>
      {/* @ts-ignore */}
      <RaImageInput accept="image/*">
        {
          /** @ts-ignore */
          React.cloneElement(children, {
            // @ts-ignore
            ...children.props,
            title,
            source,
            record: {
              ...record,
              [source]: file?.title || get(record, source),
              [`_${source}`]: file?.src || get(record, `_${source}`)
            }
          })
        }
      </RaImageInput>
    </LabeledInput>
  );
}

export { ImageInput };
export type { ImageInputProps };
