import React from 'react';
import { observer } from 'mobx-react-lite';
import { Box, Dropdown, listItemSelectBuilder } from '@wix/design-system';
import { CustomFieldModalState } from '@wix/bex-core';
import { useWixPatternsContainer } from '@wix/bex-core/react';
import { getFieldTypeIcon } from '../../utils/fieldTypePrefixIcons';

export interface CustomFieldTypeDropdownProps {
  state: CustomFieldModalState;
}

export const _CustomFieldTypeDropdown = (
  props: CustomFieldTypeDropdownProps,
) => {
  const {
    state: {
      form: {
        $: { type, name },
      },
      mode,
      fieldManagement: { creatableFieldTypes },
      generateUniqueKey,
      setKeyFieldIfNotDirty,
    },
  } = props;

  const { translate: t } = useWixPatternsContainer();

  const fieldTypeOptions = React.useMemo(
    () =>
      creatableFieldTypes.map((option) =>
        listItemSelectBuilder({
          dataHook: `custom-field-modal-type-${option.id}`,
          id: option.id,
          prefix: (
            <Box>
              {getFieldTypeIcon({
                fieldType: option.patternsType,
                size: 'medium',
              })}
            </Box>
          ),
          title: option.label,
          label: option.label,
        }),
      ),
    [creatableFieldTypes],
  );

  return (
    <Dropdown
      dataHook="custom-field-modal-type"
      disabled={mode === 'edit'}
      valueParser={(option) => option.label}
      selectedId={type.value}
      onSelect={({ id }) => {
        type.onChange(String(id));
        setKeyFieldIfNotDirty(generateUniqueKey(name.value));
      }}
      popoverProps={{ appendTo: 'window', zIndex: 5001 }}
      dropdownWidth="258px"
      placeholder={t(
        'cairo.customFields.addCustomField.modal.fieldType.placeholder',
      )}
      options={fieldTypeOptions}
    />
  );
};

export const CustomFieldTypeDropdown = observer(_CustomFieldTypeDropdown);
