import React, { Children } from 'react';
import { useRecordContext } from 'react-admin';
import { useFormContext } from 'react-hook-form';

interface FieldProps {
  source: string;
  children: React.ReactNode;
}

interface ChildProps {
  source: string;
  record: Record<string, any>;
}

function Field({ source, children }: FieldProps): JSX.Element | null {
  const Child = Children.only(children) as React.ReactElement<ChildProps>;
  const { getValues } = useFormContext();
  const record = useRecordContext({ record: getValues() });

  return React.isValidElement(Child) ? React.cloneElement(Child, { source, record }) : null;
}

export { Field };
