import React, { useEffect, useRef } from 'react';
import { SilkeBox } from '../silke-box';
import { SilkeTextSmall } from '../silke-text';
import { SilkeIcon } from '../silke-icon';
import { ConditionSuggestion } from './types';
import styles from './silke-conditions-input.scss';

export type SilkeConditionsInputProps = {
  suggestions: ConditionSuggestion[];
  highlightedItem: number;
  onSelect: (value: ConditionSuggestion) => void;
};

export function SilkeConditionsInputOptions(props: SilkeConditionsInputProps) {
  const { suggestions, highlightedItem, onSelect } = props;
  const dropdownRef = useRef<HTMLElement>();

  useEffect(() => {
    if (highlightedItem !== undefined) {
      dropdownRef.current?.children.item(highlightedItem)?.scrollIntoView(false);
    }
  }, [highlightedItem]);

  return (
    <SilkeBox
      role="listbox"
      column
      bg="neutral-20"
      style={{ maxHeight: 300 }}
      scroll
      tabIndex={-1}
      ref={dropdownRef}
      className={styles.conditionDropdown}
    >
      {suggestions.map((suggestion, i) => {
        return typeof suggestion === 'string' ? (
          <SilkeBox key={`${suggestion}-${i}`} pad="s">
            <SilkeTextSmall color="neutral-60" weight="strong">
              {suggestion}
            </SilkeTextSmall>
          </SilkeBox>
        ) : (
          <SilkeBox
            data-index={i}
            key={String(suggestion.value)}
            className={styles.suggestion}
            bgHover="surface-2"
            vPad="xs"
            hPad="s"
            bg={i === highlightedItem ? 'surface-2' : undefined}
            onMouseDown={() => {
              onSelect(suggestion);
            }}
          >
            <SilkeBox
              key={`${suggestion.label}-${suggestion.value}`}
              gap="s"
              vAlign="center"
              overflow="hidden"
              fill
            >
              <SilkeBox
                size="xs"
                hAlign
                vAlign
                rounded="tiny"
                style={
                  suggestion.type === 'color' ? { backgroundColor: suggestion.subLabel } : undefined
                }
              >
                {suggestion.type !== 'color' && (
                  <SilkeIcon color="neutral-70" icon={suggestion.icon || 'add'} />
                )}
              </SilkeBox>

              <SilkeBox column style={{ minWidth: '0', flex: 1 }}>
                <SilkeTextSmall overflow style={{ marginBottom: '-2px' }}>
                  {suggestion.label}
                </SilkeTextSmall>
              </SilkeBox>
            </SilkeBox>
          </SilkeBox>
        );
      })}
    </SilkeBox>
  );
}
