import { useCallback, useState } from 'react';

import type { FC } from 'react';
import type { SelectProps } from '../Select';

import useTheme from '~/src/hooks/useTheme';
import Box from '../Box';
import HoverBackground from '../HoverBackground';
import TriangleIcon from '../Icon/TriangleIcon';
import Select from '../Select';
import Text from '../Text';
import {
  TEXT_INPUT_DEFAULT_FONT_SIZE,
  TEXT_INPUT_DEFAULT_HEIGHT,
  TEXT_INPUT_HORIZONTAL_PADDING,
} from '../TextInput';

export interface SelectInputProps extends Omit<SelectProps, 'onChange'> {
  fontSize?: string | number;
  height?: string | number;
  isBold?: boolean;
  onChange?: SelectProps['onChange'];
}

/**
 * @deprecated Use Select2 instead
 */
const SelectInput: FC<SelectInputProps> = ({
  height = TEXT_INPUT_DEFAULT_HEIGHT,
  fontSize = TEXT_INPUT_DEFAULT_FONT_SIZE,
  isBold,
  onChange,
  items,
  value,
  defaultValue,
  ...selectProps
}) => {
  const theme = useTheme();
  const initialValue = defaultValue ?? value ?? items[0];
  const initialItem = items.find(({ id }) => id === initialValue);
  const [selectedId, setSelectedId] = useState(initialItem?.id);
  const text = items.find(({ id }) => id === (value || selectedId))?.text;

  return (
    <HoverBackground selectorFromFocusableEl="~ .selectContent">
      <Select
        {...selectProps}
        items={items}
        defaultValue={defaultValue}
        withFocusStyle={false}
        onChange={useCallback(
          (id) => {
            // keep an internal reference to the selected value so that we
            // can resolve text when the input is 'uncontrolled' (ie. no `value` prop)
            setSelectedId(id);

            if (onChange) {
              onChange(id);
            }
          },
          [onChange]
        )}
      >
        <Box
          alignCenter
          positionRelative
          flexRow
          style={{
            background: theme.textInputBackground,
            borderRadius: theme.borderRadius,
            border: `solid 1px ${theme.textInputBorderColor}`,
            fontSize,
            height,
          }}
        >
          <Text
            size="1em"
            padding={`0 ${TEXT_INPUT_HORIZONTAL_PADDING}`}
            color={theme.textColor90}
            isBold={isBold}
          >
            {text}
          </Text>
          <TriangleIcon
            size="0.66em"
            color={theme.textColor60}
            direction="down"
            positionAbsolute
            right={0}
            top="50%"
            margin="-0.3em 0.7em 0"
          />
        </Box>
      </Select>
    </HoverBackground>
  );
};

export default SelectInput;
