// Copyright 1999-2023. Plesk International GmbH. All rights reserved.

import classNames from 'classnames';
import { Fragment, useRef, useState, useLayoutEffect, forwardRef } from 'react';
import { useTranslate } from '../LocaleProvider';
import { CLS_PREFIX } from '../../constants';
import Icon from '../Icon';
import MultiValue from './MultiValue';
import { jsx as _jsx } from "react/jsx-runtime";
import { jsxs as _jsxs } from "react/jsx-runtime";
const DEFAULT_INPUT_WIDTH = 2;
let inputMeter;
const getInputWidth = target => {
  if (!inputMeter) {
    inputMeter = document.createElement('pre');
    document.body.appendChild(inputMeter);
  }
  const targetStyle = window.getComputedStyle(target);
  inputMeter.style.fontFamily = targetStyle.fontFamily;
  inputMeter.style.fontSize = targetStyle.fontSize;
  inputMeter.style.padding = '0';
  inputMeter.style.display = 'inline-block';
  inputMeter.style.width = 'auto';
  inputMeter.style.position = 'absolute';
  inputMeter.style.right = '0';
  inputMeter.style.top = '-9999px';
  inputMeter.style.visibility = 'hidden';
  inputMeter.textContent = target.value;
  const {
    width
  } = inputMeter.getBoundingClientRect();
  return width || DEFAULT_INPUT_WIDTH;
};
const SelectControl = /*#__PURE__*/forwardRef(function SelectControl(_ref, ref) {
  let {
    baseClassName = `${CLS_PREFIX}select-control`,
    id,
    name,
    current,
    disabled,
    searchable,
    clearable,
    multiple,
    filterValue,
    onFilterChange,
    onHighlightChange,
    onHighlightConfirm,
    onHighlightSearch,
    onOpen,
    onClose,
    onClear,
    onValueRemove,
    placeholder,
    ...props
  } = _ref;
  const inputRef = useRef(null);
  const searchBufferValue = useRef('');
  const searchBufferTimer = useRef(0);
  const [inputWidth, setInputWidth] = useState(DEFAULT_INPUT_WIDTH);
  const [focused, setFocused] = useState(false);
  const translate = useTranslate();
  if (placeholder === undefined) {
    placeholder = translate('Select.placeholder', undefined, 'Select...');
  }
  let values = [];
  if (Array.isArray(current)) {
    values = current.map(_ref2 => {
      let {
        value
      } = _ref2;
      return value;
    });
  } else if (current) {
    values = [current.value];
  }
  const hasValue = values.length > 0;
  useLayoutEffect(() => {
    if (filterValue === '') {
      setInputWidth(DEFAULT_INPUT_WIDTH);
    }
  }, [filterValue]);
  const handleClick = () => {
    if (disabled) {
      return;
    }
    onOpen();
    if (inputRef.current) {
      inputRef.current.focus();
    }
  };
  const handleInputChange = e => {
    const width = getInputWidth(e.target);
    setInputWidth(width);
    onFilterChange(e.target.value);
  };
  const handleValueRemove = value => {
    onValueRemove(value);
  };
  const handleClear = () => {
    onClear();
  };
  const handleKeyDown = e => {
    switch (e.key) {
      case 'ArrowUp':
        e.preventDefault();
        onHighlightChange(-1);
        break;
      case 'ArrowDown':
        e.preventDefault();
        onHighlightChange(1);
        break;
      case 'PageUp':
        e.preventDefault();
        onHighlightChange(-10);
        break;
      case 'PageDown':
        e.preventDefault();
        onHighlightChange(10);
        break;
      case 'Enter':
        e.preventDefault();
        onHighlightConfirm();
        break;
      case 'Escape':
        e.preventDefault();
        onFilterChange('');
        onClose();
        break;
      case 'Backspace':
        if (filterValue === '') {
          if (multiple) {
            handleValueRemove();
          } else if (clearable) {
            handleValueRemove();
          }
        }
        break;
      default:
        if (!searchable && e.key.length === 1) {
          searchBufferValue.current += e.key;
          onHighlightSearch(searchBufferValue.current);
          window.clearTimeout(searchBufferTimer.current);
          searchBufferTimer.current = window.setTimeout(() => {
            searchBufferValue.current = '';
          }, 1000);
        }
        break;
    }
  };
  const handleFocus = () => {
    setFocused(true);
  };
  const handleBlur = () => {
    setFocused(false);
  };
  return /*#__PURE__*/_jsxs("div", {
    className: classNames(baseClassName, {
      [`${baseClassName}--disabled`]: disabled,
      [`${baseClassName}--focused`]: focused,
      [`${baseClassName}--multiple`]: multiple
    }),
    ...props,
    onClick: handleClick,
    ref: ref,
    children: [/*#__PURE__*/_jsxs("span", {
      className: `${baseClassName}__value-container`,
      children: [Array.isArray(current) && current.map(_ref3 => {
        let {
          value,
          label
        } = _ref3;
        return /*#__PURE__*/_jsx(MultiValue, {
          onRemove: () => handleValueRemove(value),
          children: label
        }, value);
      }), /*#__PURE__*/_jsx("input", {
        id: id,
        className: `${baseClassName}__input`,
        value: filterValue,
        type: "text",
        onChange: handleInputChange,
        onKeyDown: handleKeyDown,
        onFocus: handleFocus,
        onBlur: handleBlur,
        readOnly: !searchable,
        disabled: disabled,
        ref: inputRef,
        style: {
          width: inputWidth
        }
      }), !filterValue && /*#__PURE__*/_jsxs(Fragment, {
        children: [!Array.isArray(current) && current && /*#__PURE__*/_jsx("span", {
          className: `${baseClassName}__value`,
          children: current.children
        }), !hasValue && placeholder && /*#__PURE__*/_jsx("span", {
          className: `${baseClassName}__placeholder`,
          children: placeholder
        })]
      })]
    }), /*#__PURE__*/_jsxs("span", {
      className: `${baseClassName}__indicators`,
      children: [clearable && hasValue && /*#__PURE__*/_jsx("button", {
        type: "button",
        className: classNames(`${baseClassName}__indicator`, `${baseClassName}__indicator--clear`),
        tabIndex: -1,
        onMouseDown: e => e.preventDefault(),
        onClick: e => {
          e.stopPropagation();
          handleClear();
        },
        children: /*#__PURE__*/_jsx(Icon, {
          className: `${baseClassName}__indicator-icon`,
          children: /*#__PURE__*/_jsx("svg", {
            xmlns: "http://www.w3.org/2000/svg",
            viewBox: "-4 -4 16 16",
            "aria-hidden": "true",
            focusable: "false",
            children: /*#__PURE__*/_jsx("path", {
              d: "M.85 7.854a.498.498 0 1 1-.704-.704L3.296 4 .146.85A.498.498 0 0 1 .85.146L4 3.296 7.15.146a.498.498 0 0 1 .704.704L4.704 4l3.15 3.15a.498.498 0 0 1-.704.704L4 4.704.85 7.854z"
            })
          })
        })
      }), /*#__PURE__*/_jsx("button", {
        type: "button",
        className: classNames(`${baseClassName}__indicator`, `${baseClassName}__indicator--dropdown`),
        tabIndex: -1,
        children: /*#__PURE__*/_jsx(Icon, {
          className: `${baseClassName}__indicator-icon`,
          children: /*#__PURE__*/_jsx("svg", {
            xmlns: "http://www.w3.org/2000/svg",
            viewBox: "-4 -5 16 16",
            "aria-hidden": "true",
            focusable: "false",
            children: /*#__PURE__*/_jsx("path", {
              d: "M4 4.048L.847.895a.496.496 0 1 0-.702.702l3.452 3.451a.5.5 0 0 0 .806 0l3.452-3.451a.496.496 0 0 0-.702-.702L4 4.048z"
            })
          })
        })
      })]
    }), name && values.map(value => /*#__PURE__*/_jsx("input", {
      type: "hidden",
      name: name,
      value: value
    }, value))]
  });
});
SelectControl.displayName = 'SelectControl';
export default SelectControl;