import React, { useEffect } from 'react';
import { Button, FormControl, Panel } from 'react-bootstrap';
import { useForm, FormProvider } from 'react-hook-form';
import FieldAlert from '../Form/FieldAlert';
import TextFieldGroup from '../Form/TextFieldGroup';
import { ITEM_TYPE_DEFS } from '../../constants';

function ItemForm(props) {
  const { item, samples, bsStyle, onSubmit, onCancel } = props;
  const methods = useForm({ defaultValues: item });
  const {
    handleSubmit,
    errors,
    register,
    formState,
    watch,
    setValue,
  } = methods;
  const { isSubmitting } = formState;

  const sampleDescriptions = Object.fromEntries(
    samples.map((s) => [
      s.id,
      (s.parameters.desc && s.parameters.desc.value) || '',
    ])
  );

  const watchedItemIsSample = watch('type') === 'SAMPLESHEET';
  const watchedSampleId = watch('sampleId');

  useEffect(() => {
    // Remove stale description if no sample and sampleId (occurs when changing to Tool or Other from a selected Sample)
    if (!watchedItemIsSample && watchedSampleId) {
      setValue('description', '');
    }
  });

  return (
    <Panel bsStyle={bsStyle}>
      <Panel.Body>
        <FormProvider {...methods}>
          {item && <input name="_id" type="hidden" ref={register} />}
          <TextFieldGroup
            registerOptions={{ required: true }}
            name="name"
            type="text"
          />

          <FormControl
            style={{ marginBottom: '1rem' }}
            name="type"
            componentClass="select"
            inputRef={register({ required: true })}
          >
            <option value="">Select item type...</option>
            {Object.entries(ITEM_TYPE_DEFS).map(([type, { optionLabel }]) => (
              <option key={type} value={type}>
                {optionLabel}
              </option>
            ))}
          </FormControl>
          {errors?.type && <FieldAlert fieldLabel="type" error={errors.type} />}

          {watchedItemIsSample && (
            <>
              <FormControl
                style={{ marginBottom: '1rem' }}
                name="sampleId"
                componentClass="select"
                inputRef={register({ required: true })}
                onChange={() => {
                  if (watchedSampleId) {
                    setValue(
                      'description',
                      sampleDescriptions[watchedSampleId]
                    );
                  }
                }}
              >
                <option value="">Select sample...</option>
                {samples.map((sample) => (
                  <option key={sample.id} value={sample.id}>
                    {sample.name}
                  </option>
                ))}
              </FormControl>
              {errors?.sampleId && (
                <FieldAlert fieldLabel="Sample" error={errors.sampleId} />
              )}
            </>
          )}
          <TextFieldGroup
            name="description"
            label={`Description${watchedItemIsSample ? ' (from sample)' : ''}`}
            type="text"
            disabled={watchedItemIsSample}
          />
          <TextFieldGroup name="comments" type="textarea" />
        </FormProvider>
      </Panel.Body>
      <Panel.Footer>
        <Button
          bsStyle="primary"
          onClick={handleSubmit(onSubmit)}
          disabled={isSubmitting}
        >
          {isSubmitting ? 'Saving...' : 'Save'}
        </Button>
        <Button bsStyle="link" onClick={onCancel} disabled={isSubmitting}>
          Cancel
        </Button>
      </Panel.Footer>
    </Panel>
  );
}

export default ItemForm;
