import { RefObject } from 'react';

import { FormGroup } from '@/components/form/FormGroup';
import { SelectSingle } from '@/components/select/SelectSingle';

import { useFormidableContextElement } from '../formidable';

export type FormSelectProps = {
  // Form: Name of the variable
  name: string;
  // Forward object reference
  ref?: RefObject<any>;
  // Form: Label of the input
  label?: string;
  // Form: Placeholder if nothing is selected
  placeholder?: string;
  // Form: Specify if the element is required or not
  isRequired?: boolean;
  // is locked for edition
  disabled?: boolean;
  // List of object options
  options: object[];
  // in the option specify the value Key
  keyInputKey?: string;
  // in the option specify the value field
  keyInputValue?: string;
  // Add capability to add an item (no key but only value)
  addNewItem?: (data: string) => Promise<any>;
  // if a suggestion exist at the auto compleat
  suggestion?: string;
};

export const FormSelect = ({
  name,
  ref,
  placeholder,
  options,
  keyInputKey = 'id',
  keyInputValue = 'name',
  disabled = false,
  suggestion,
  addNewItem,
  ...rest
}: FormSelectProps) => {
  const { form, value, isModify, onChange, onRestore } =
    useFormidableContextElement(name);
  // if set add capability to add the search item
  const onCreate = !addNewItem
    ? undefined
    : (data: string) => {
        addNewItem(data).then((data: object) =>
          form.setValues({ [name]: data[keyInputKey] })
        );
      };
  return (
    <FormGroup name={name} {...rest}>
      <SelectSingle
        ref={ref}
        value={value}
        options={options}
        onChange={(value) => onChange(value)}
        keyKey={keyInputKey}
        keyValue={keyInputValue}
        onCreate={onCreate}
        suggestion={suggestion}
        disabled={disabled}
      />
    </FormGroup>
  );
};
