what is going on in this code? import React, { useCallback, useMemo, useState } from 'react';
import PropTypes from 'prop-types';
import { Combobox, comboboxAddSubheadings, comboboxFilterAndLimit, Tooltip } from '@salesforce/design-system-react';
import { get } from 'lodash';
import {
	localize,
	DATA_ATTRIBUTE_TOOLTIP,
	DATA_ATTRIBUTE,
	DATA_ATTRIBUTE_PLACEHOLDER,
	DATA_ATTRIBUTE_CREATE_DE_NOT_SELECTED,
	CREATE_NEW_ATTRIBUTE
} from '../../../../utilities/localizations';
import DeAttributeList from '../../de-attribute-functions';
import { NewDeAttribute } from '../../../icons/svg-icons';
import NewDataAttributeComponent from '../new-de-attribute/new-de-attribute';
import { useEmailContext } from '../../../../providers/email/email-provider';
import './select-existing-de.scss';

export const CreateDaId = 'add-data-attribute';
const DATA_ATTRIBUTE_PATH = 'metadata.dataAttribute';

export const SelectExistingDeComponent = ({
	attributes,
	value,
	disabled,
	errorText,
	onChange,
	onCreate,
	logEventIntoGA
}) => {
	const createHeader = (attributeType) => ({
		id: attributeType,
		label: localize(`${attributeType.toUpperCase()}_ATTRIBUTES`),
		type: 'separator'
	});

	const subheadings = () => {
		const attributeArray = [];
		const subheaders = { required: false, optional: false };

		for (let i = 0; i < attributes.length; i++) {
			const attributeType = attributes[i].type;
			if (subheaders.required && subheaders.optional) {
				return attributeArray;
			}
			
			if (!subheaders[attributeType]) {
				subheaders[attributeType] = true;
				if (attributeType === 'optional') {
					attributeArray.push(createHeader(attributeType));
				} else if (attributeType === 'required') {
					attributeArray.unshift(createHeader(attributeType));
				}
			}
		}
		return attributeArray;
	};

	const updateField = (e, { selection }) => {
		if (selection[0]) {
			if (selection[0].id === CreateDaId) {
				onCreate();
				logEventIntoGA('Create', 'Data Extension: New Attribute', 'content');
			} else if (selection[0].attribute) {
				onChange(DATA_ATTRIBUTE_PATH, selection[0].attribute);
				logEventIntoGA('Select', 'Data Extension: Existing Attribute', 'content');
			}
		}
	};

	const removeAttribute = () => {
		onChange(DATA_ATTRIBUTE_PATH, undefined);
	};

	const currentSelection = value ? [{
		id: value.id,
		label: value.name,
		subTitle: value.type,
		type: value.isNullable ? 'optional' : 'required'
	}] : [];

	const tooltip = useMemo(() => (
		<Tooltip
			align="top left"
			position="overflowBoundaryElement"
			content={DATA_ATTRIBUTE_TOOLTIP}
			variant="learnMore"
		/>
	), []);

	const options = disabled ? [] : [...comboboxAddSubheadings({
		subheadings: subheadings(),
		filteredOptions: comboboxFilterAndLimit({
			inputValue: value && value.name,
			options: attributes,
			limit: attributes.length,
			selection: currentSelection
		})
	}), {
		id: 'new',
		type: 'separator'
	}];

	return (
		<Combobox
			required
			events={{
				onRequestRemoveSelectedOption: removeAttribute,
				onSelect: updateField,
				onSubmit: updateField
			}}
			labels={{
				label: DATA_ATTRIBUTE,
				placeholder: DATA_ATTRIBUTE_PLACEHOLDER,
				noOptionsFound: DATA_ATTRIBUTE_CREATE_DE_NOT_SELECTED
			}}
			fieldLevelHelpTooltip={tooltip}
			options={options}
			selection={currentSelection}
			value={(value && value.name) || ''}
			variant="inline-listbox"
			errorText={errorText}
			multiple={false}
			predefinedOptionsOnly
			menuItemVisibleLength={7}
			optionsAddItem={disabled ? [] : [{
				id: CreateDaId,
				icon: (<NewDeAttribute />),
				label: CREATE_NEW_ATTRIBUTE
			}]}
		/>
	);
};

SelectExistingDeComponent.propTypes = {
	attributes: PropTypes.arrayOf(PropTypes.object).isRequired,
	errorText: PropTypes.string,
	disabled: PropTypes.bool,
	onChange: PropTypes.func.isRequired,
	onCreate: PropTypes.func.isRequired,
	logEventIntoGA: PropTypes.func.isRequired,
	value: PropTypes.oneOfType([
		PropTypes.object,
		PropTypes.bool
	])
};

// This is split in two separate components in order to help separate some of the logic
// The important thing is that the validation logic lives at the top, that way the component
// is validated on every change, including when a new attribute is created
const SelectExistingDe = ({ context, onChange, disableRequiredDE }) => {
	const value = get(context, DATA_ATTRIBUTE_PATH);
	const errorText = get(context, `metadata.errors.["${DATA_ATTRIBUTE_PATH}"]`);
	const [isOpen, setIsOpen] = useState(false);
	const open = useCallback(() => setIsOpen(true), []);
	const { state, logEventIntoGA, addAttribute, getCurrentDE, getFields } = useEmailContext();
	const fields = getFields();
	const currentDe = getCurrentDE();

	const onCreate = (dataAttribute) => {
		addAttribute(dataAttribute);
		onChange(DATA_ATTRIBUTE_PATH, dataAttribute);
		setIsOpen(false);
	};

	const dataExtensionId = currentDe && currentDe.id;

	if (isOpen) {
		return (
			<NewDataAttributeComponent
				fields={fields}
				onCancel={() => setIsOpen(false)}
				onCreate={onCreate}
				dataExtensionId={dataExtensionId}
			/>
		);
	}

	const attributes = DeAttributeList(fields, disableRequiredDE, [...state.components.visibleInputs, ...state.components.hiddenInputs]);

	return (
		<SelectExistingDeComponent
			attributes={attributes}
			onCreate={open}
			onChange={onChange}
			context={context}
			disabled={!dataExtensionId}
			value={value}
			errorText={errorText}
			logEventIntoGA={logEventIntoGA}
		/>
	);
};

SelectExistingDe.propTypes = {
	context: PropTypes.object,
	onChange: PropTypes.func.isRequired,
	disableRequiredDE: PropTypes.bool.isRequired
};

export default SelectExistingDe;
