import React, { HTMLAttributes, MutableRefObject } from "react";
import classNames from "classnames";
import { UseSelectGetItemPropsOptions } from "downshift";
import { Flex } from "../../Flex";
import { Icon, ICON_TYPE } from "../../Icon";
import { SelectOption } from "./types";
import { List } from "../../List";

interface CreatableOptionProps<T> extends HTMLAttributes<HTMLDivElement> {
  label: string;
  isCreatable: boolean;
  optionIndexRef: MutableRefObject<number>;
  setOptionIndex: (newIndex: number) => void;
  highlightedIndex: number;
  getItemProps: (options: UseSelectGetItemPropsOptions<T | null>) => any;
  creatableOption: T;
}

export function CreatableOption<T extends SelectOption>({
  onClick,
  optionIndexRef,
  setOptionIndex,
  highlightedIndex,
  label,
  isCreatable,
  getItemProps,
  creatableOption,
}: CreatableOptionProps<T>) {
  if (!isCreatable) return null;

  const optionIndex = optionIndexRef.current;
  setOptionIndex(optionIndexRef.current + 1);
  const isHighlighted = highlightedIndex === optionIndex;

  return (
    <List.Item
      className={classNames(
        "px-3",
        "py-2",
        "flex",
        "items-center",
        "justify-between",
        isHighlighted && "bg-gray-400",
      )}
      {...getItemProps({
        item: creatableOption,
        index: optionIndex,
      })}
      onClick={onClick}
    >
      <Flex
        className={classNames(
          "h-6",
          "items-center",
          highlightedIndex === 0 && "text-link",
        )}
      >
        <Icon icon={ICON_TYPE.PLUS_CIRCLE} className="mr-1" />
        {`Create "${label}"`}
      </Flex>
    </List.Item>
  );
}
