import React, { ComponentType, LegacyRef } from 'react';
import classNames from 'classnames';
import FileList from './FileList';
import { InjectedFieldProps } from '../Field/InjectedFieldProps';
import { FormDefaults } from '../FormDefaults';
import Group, { GroupProps } from '../Group';

export interface FileGroupProps
  // note: file props are of type "any" with the current type generation
  extends InjectedFieldProps<any | undefined | null>,
    Omit<GroupProps, keyof InjectedFieldProps<any> | 'children'>,
    Omit<
      React.HTMLProps<HTMLInputElement>,
      keyof InjectedFieldProps<any> | 'children' | 'className' | 'label'
    > {
  /** Allow multiple files to be uploaded. */
  multiple?: boolean | undefined;
}

function FileGroup(
  {
    input,
    meta,
    label,
    helpText,
    className,
    required,
    disabled,
    multiple,
    ...rest
  }: FileGroupProps,
  ref: LegacyRef<HTMLInputElement>
) {
  return (
    <Group
      input={input}
      meta={meta}
      label={label}
      helpText={helpText}
      className={classNames(
        className,
        { [FormDefaults.cssClassPrefix + 'multiple']: multiple },
        FormDefaults.cssClassPrefix + 'file-group'
      )}
      required={required}
      disabled={disabled}>
      <input
        {...input}
        {...rest}
        multiple={multiple}
        onChange={(e) => {
          if (!e?.target?.files?.length) {
            input.onChange(undefined);
          } else {
            const files: File[] = [];
            for (let i = 0; i < e.target.files.length; i++) {
              files.push(e.target.files[i]);
            }
            if (!multiple) {
              input.onChange(files[0]);
            } else {
              input.onChange(files);
            }
          }
        }}
        value={undefined}
        ref={ref}
        type="file"
        className={classNames(
          className,
          FormDefaults.cssClassPrefix + 'file-group'
        )}
      />
      {/* Note: because input.value is any - due to how files are currently handled - type safeness isn't great here */}
      <FileList files={input.value} />
    </Group>
  );
}

/** File upload input group.  */
const FileGroupWithRef = React.forwardRef(
  FileGroup
) as ComponentType<FileGroupProps>;

export default FileGroupWithRef;
