import { Column, SelectField } from '@8base/boost';
import cx from 'classnames';
import React, { useCallback } from 'react';

import { IOption } from 'types';

import List from '../list';

// -- TYPES

export interface ISelectBrowserProps<OptionBodyProps = IOption> {
  input: {
    value: any;
    onChange?: (value: any) => any;
  };
  className: {
    list?: string;
  };
  options: IOption[];
  availableOptions: OptionBodyProps[];
  onItemSelect: (option: IOption) => any;
  onInputChange?: (value: string, meta: { action: string }) => any;
  label?: string;
  optionBody?: React.ComponentType<OptionBodyProps>;
  inputValue?: string;
  placeholder?: string;
  loading?: boolean;
  multiple?: boolean;
}

export interface ISelectBrowserListItemProps extends IOption {
  onItemSelect: ISelectBrowserProps['onItemSelect'];
  children: React.ReactNode;
}

// -- COMPONENTS

function SelectBrowserListItem({
  label,
  value,
  onItemSelect,
  children,
}: ISelectBrowserListItemProps) {
  const onClick = useCallback(() => {
    onItemSelect({ label, value });
  }, []);

  return <List.Item onClick={onClick}>{children}</List.Item>;
}

// -- MAIN

function SelectBrowser<OptionBodyProps extends IOption>({
  availableOptions,
  onItemSelect,
  loading,
  className,
  optionBody: OptionBody,
  ...selectProps
}: ISelectBrowserProps<OptionBodyProps>) {
  const cnList = cx(className.list);

  return (
    <Column gap="sm" alignItems="stretch">
      <SelectField stretch={true} menuIsOpen={false} {...selectProps} />

      {loading ? (
        <div>Loading...</div>
      ) : (
        <List className={cnList}>
          {availableOptions.map(option => (
            <SelectBrowserListItem
              key={option.value}
              onItemSelect={onItemSelect}
              {...option}
            >
              {OptionBody ? <OptionBody {...option} /> : option.label}
            </SelectBrowserListItem>
          ))}
        </List>
      )}
    </Column>
  );
}

SelectBrowser.defaultProps = {
  className: {},
};

export default SelectBrowser;
