import React, {ReactElement, ReactNode, useRef, useState} from 'react';
import {FocusScope, useFocusManager} from '@react-aria/focus';
import {ListItemBase, ListItemBaseProps} from './list-item-base';
import clsx from 'clsx';

interface Props {
  className?: string;
  children: ReactElement<ListItemProps> | ReactElement<ListItemProps>[];
}

export function List({children, className}: Props) {
  return (
    <FocusScope>
      <ul className={clsx('py-4 text-base sm:text-sm outline-none', className)}>
        {children}
      </ul>
    </FocusScope>
  );
}

interface ListItemProps extends ListItemBaseProps {
  children: ReactNode;
  onSelected?: () => void;
  borderRadius?: string;
}
export function ListItem({
  children,
  onSelected,
  borderRadius,
  ...listItemProps
}: ListItemProps) {
  const focusManager = useFocusManager();
  const isSelectable = !!onSelected;
  const ref = useRef<HTMLDivElement>(null);
  const [isActive, setIsActive] = useState(false);

  const onKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {
    switch (e.key) {
      case 'ArrowDown':
        e.preventDefault();
        focusManager.focusNext();
        break;
      case 'ArrowUp':
        e.preventDefault();
        focusManager.focusPrevious();
        break;
      case 'Home':
        e.preventDefault();
        focusManager.focusFirst();
        break;
      case 'End':
        e.preventDefault();
        focusManager.focusLast();
        break;
      case 'Enter':
      case 'Space':
        e.preventDefault();
        onSelected?.();
        break;
    }
  };

  return (
    <li>
      <ListItemBase
        className={borderRadius || 'rounded'}
        isActive={isActive}
        isDisabled={listItemProps.isDisabled}
        {...listItemProps}
        onFocus={e => {
          setIsActive((e.target as HTMLElement).matches(':focus-visible'));
        }}
        onBlur={() => {
          setIsActive(false);
        }}
        onClick={() => {
          onSelected?.();
        }}
        ref={ref}
        role={isSelectable ? 'button' : undefined}
        onKeyDown={isSelectable ? onKeyDown : undefined}
        tabIndex={isSelectable && !listItemProps.isDisabled ? 0 : undefined}
      >
        {children}
      </ListItemBase>
    </li>
  );
}
