import React, { useCallback } from 'react';
import { observer } from 'mobx-react-lite';
import { Cell, Layout } from '@wix/design-system';
import { CustomField, CustomFieldType } from '@wix/bex-core';
import { EDITABLE_INPUT_ELEMENTS, FormFieldInput } from '../FormFieldInput';
import { CustomFieldsFormState } from '../../state';
import { CustomFieldsFormContextProvider } from '../CustomFieldsFormContext';
import { OnCustomFieldChange } from '../CustomFieldsWidget/OnCustomFieldChange';

export interface CustomFieldsFormProps {
  state: CustomFieldsFormState;
  onChange?: OnCustomFieldChange;
}

const toCellSpan = (type?: CustomFieldType) => {
  switch (type) {
    case 'longText':
    case 'checkbox':
    case 'shortText':
    case 'url':
    case 'dateTime':
      return 12;
    default:
      return 6;
  }
};

const _CustomFieldsForm = ({ state, onChange }: CustomFieldsFormProps) => {
  const { _namespace } = state;
  const renderFieldInput = useCallback((field: CustomField) => {
    if (!field) {
      return null;
    }

    if (!EDITABLE_INPUT_ELEMENTS.hasOwnProperty(field.type)) {
      return null;
    }

    const span = toCellSpan(field.type);

    return (
      <React.Fragment key={field.id}>
        <Cell span={span}>
          <FormFieldInput
            dataHook={`field-${field.id}`}
            state={state}
            schema={field}
            initialValue={state.getInitialValue(field.id)}
            onChange={(newValue) =>
              state.setValue({ id: field.id, value: newValue, onChange })
            }
            inputRef={(inputRef) => {
              state.setInputRef(field.id, inputRef);
            }}
          />
        </Cell>
        {span !== 12 && <Cell span={12 - span} />}
      </React.Fragment>
    );
  }, []);

  const { writeableFields } = state;

  return (
    <CustomFieldsFormContextProvider value={state}>
      <Layout dataHook={`custom-fields-form-${_namespace}`} gap="SP3">
        {writeableFields.map(renderFieldInput)}
      </Layout>
    </CustomFieldsFormContextProvider>
  );
};

export const CustomFieldsForm = observer(_CustomFieldsForm);
