import React, { ComponentType } from 'react';
import {
  BaseInputProps,
  Checkbox,
  DateInput,
  DateTime,
  Dropdown,
  LongText,
  Number,
  ShortText,
} from '../../fields';
import { CustomField, CustomFieldType } from '@wix/bex-core';
import { CustomFieldsFormState } from '../../state';
import { Url } from '../../fields/Url';

type InputElements = {
  [fieldType in CustomFieldType]: ComponentType<BaseInputProps<any>>;
};

export const EDITABLE_INPUT_ELEMENTS = {
  dropdown: Dropdown,
  checkbox: Checkbox,
  shortText: ShortText,
  longText: LongText,
  date: DateInput,
  dateTime: DateTime,
  integer: Number,
  decimal: Number,
  url: Url,
};

const INPUT_ELEMENTS: InputElements = {
  ...EDITABLE_INPUT_ELEMENTS,
  files: () => null, // not supported
  multiSelect: () => null, // not supported
};

export interface FormFieldInputProps {
  dataHook?: string;
  state: CustomFieldsFormState;
  initialValue?: any;
  schema: CustomField;
  onChange: (newValue: any) => void;
  inputRef?: BaseInputProps<any>['inputRef'];
}

export const FormFieldInput = ({
  dataHook,
  state,
  schema,
  initialValue,
  onChange,
  inputRef,
}: FormFieldInputProps) => {
  if (INPUT_ELEMENTS.hasOwnProperty(schema.type)) {
    const FieldInput = INPUT_ELEMENTS[schema.type];

    return (
      <FieldInput
        dataHook={dataHook}
        state={state}
        initialValue={initialValue}
        schema={schema}
        onChange={(newValue) => onChange(newValue)}
        inputRef={inputRef}
      />
    );
  }

  return null;
};
