/**
 * Copyright 2024 Phenix Real Time Solutions, Inc. Confidential and Proprietary. All Rights Reserved.
 */
import React, {useState, useRef, useEffect, ChangeEvent} from 'react';

import {Label} from 'components/label';

import {ISelectItem} from 'interfaces';

import {SelectContainer, SubLabel} from './style';

export interface ISelectComponent {
  label?: string;
  labelColor?: string;
  labelHtmlFor?: string;
  items: ISelectItem[];
  onSelect: (item: ISelectItem) => void;
  defaultItems: ISelectItem[]; // TODO change to defaultItem: ISelectItem and change subLabel to helperText (#CC-526)
  subLabel?: string;
  width?: number | string; // TODO check after refactoring if it possible restrict width
}

const SelectComponent = ({label, items, onSelect, defaultItems, subLabel, labelColor, labelHtmlFor, width}: ISelectComponent): React.JSX.Element => {
  const [selectedItems, setSelectedItems] = useState(defaultItems);
  const [focusOnSelectComponent, setFocusOnSelectComponent] = useState(false);
  const optsRef = useRef([]);

  useEffect(() => {
    onSelect(selectedItems[0]);
  }, [selectedItems, onSelect]);

  useEffect(() => {
    if (optsRef.current[0]) {
      optsRef.current[0].focus();
    }
  }, [focusOnSelectComponent]);

  const handleFocus = () => {
    setFocusOnSelectComponent(true);
  };

  const generateOptions = () =>
    items.map(({label, value}) => (
      <option value={value} key={label}>
        {label}
      </option>
    ));
  const onSelectItem = (event: ChangeEvent<HTMLSelectElement>) => {
    const {target} = event;
    const item = items.filter(({value}) => {
      return target.value === value;
    })[0];

    setSelectedItems([item]);
  };

  return (
    <SelectContainer onFocus={handleFocus} tabIndex={0} width={width}>
      {!!label && <Label text={label} color={labelColor} htmlFor={labelHtmlFor} />}
      <select defaultValue={defaultItems[0].value} onChange={onSelectItem} className="testId-selectElement">
        {generateOptions()}
      </select>
      {subLabel && <SubLabel>{subLabel}</SubLabel>}
    </SelectContainer>
  );
};

export default SelectComponent;
