import React, { useRef, useState } from 'react';
import { useTheme } from 'styled-components';
import { ExpandDropdownIcon } from '../../icons';
import Chip from '../Chip';
import SelectMenu from '../SelectMenu';
import { SelectOptionType } from '../SelectMenu/interfaces';
import { DropdownChipProps } from './interfaces';
import { Wrapper } from './styles';

const DropdownChip = ({
  selectedOptionLabel,
  placeholder,
  options,
  onChange,
  menuPosition = 'absolute',
  menuZIndex,
}: DropdownChipProps) => {
  const theme = useTheme();
  const [menuOpen, setMenuOpen] = useState(false);
  const wrapperElementRef = useRef<HTMLDivElement | null>(null);

  const handleOptionClick = (opt: SelectOptionType) => {
    setMenuOpen(false);
    onChange?.(opt);
  };

  return (
    <Wrapper ref={wrapperElementRef}>
      <Chip
        label={selectedOptionLabel || placeholder || 'See More'}
        selected={Boolean(selectedOptionLabel)}
        onClick={() => setMenuOpen(!menuOpen)}
        borderColor={menuOpen ? theme.colors.neutral[800] : undefined}
        icon={
          <ExpandDropdownIcon
            width={18}
            height={18}
            arrowPointsUp={menuOpen}
            color="currentColor"
          />
        }
      />

      {menuOpen && (
        <SelectMenu
          options={options}
          menuPosition={menuPosition}
          menuZIndex={menuZIndex}
          wrapperElementRef={wrapperElementRef}
          onOptionClick={handleOptionClick}
          selectedOptionLabel={selectedOptionLabel}
        />
      )}
    </Wrapper>
  );
};

export default DropdownChip;
