import React, { HTMLAttributes, ReactNode, useContext } from "react";
import classNames from "classnames";
import { Box } from "../../Box";
import { SelectOption } from "../shared/types";
import { Flex } from "../../Flex";
import { Icon, ICON_TYPE } from "../../Icon";
import { SingleSelectContext } from "./SingleSelectContext";

interface SingleSelectOptionProps<T extends SelectOption>
  extends HTMLAttributes<HTMLDivElement> {
  option: T;
  children?: ReactNode;
  isDisabled?: boolean;
}

export function SingleSelectOption<T extends SelectOption>({
  option,
  children,
  isDisabled = false,
  ...rest
}: SingleSelectOptionProps<T>) {
  const {
    getItemProps,
    selectedItem,
    highlightedIndex,
    optionIndexRef,
    setOptionIndex,
  } = useContext(SingleSelectContext);

  const optionIndex = optionIndexRef.current;
  setOptionIndex(optionIndexRef.current + 1);
  const isSelected = !!selectedItem && selectedItem.value === option.value;
  const isHighlighted = highlightedIndex === optionIndex;

  const itemProps = getItemProps({
    item: option,
    index: optionIndex,
    disabled: isDisabled,
  });

  return (
    <Box
      as="li"
      key={option.value}
      className={classNames(
        "px-3",
        "py-2",
        "flex",
        "items-center",
        "justify-between",
        isSelected && !isHighlighted && "bg-gray-300",
        isHighlighted && "bg-gray-400",
        isDisabled && "opacity-40",
        isDisabled ? "cursor-not-allowed" : "cursor-default",
      )}
      {...rest}
      {...itemProps}
    >
      {children || option.label}
      <Flex className="items-center justify-center w-6 h-6">
        {isSelected && (
          <Icon
            icon={ICON_TYPE.CHECK}
            className={classNames(
              isHighlighted ? "text-gray-700" : "text-gray-600",
            )}
          />
        )}
      </Flex>
    </Box>
  );
}
