import classNames from "classnames";
import { OptionProps } from "./types/OptionProps";
import useClickOutside from "hooks/useClickOutside";
import { OptionSelectProps } from "./types/OptionSelectProps";
import React, { FC, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useInView } from 'react-intersection-observer';
const OptionSelect: FC<OptionSelectProps> = ({ label, labelHidden, value, options, placeholder, disabled, cls, onChange, onScroll }) => {
const optionSelect = useRef<HTMLDivElement>(null);
const [open, toggleOpen] = useState<boolean>(false);
const selectedElement = options.find((option: OptionProps) => option.value == value);
const { ref, inView } = useInView({ threshold: 0 });
const optionSelectClasses = classNames('select', cls);
const optionSelectButtonClasses = classNames('select__button', {
'select__button--disabled': disabled
});
const close = useCallback(() => toggleOpen(false), []);
useClickOutside(optionSelect, close);
const handleOnChange = (value: string) => {
onChange(value);
toggleOpen(false);
}
useEffect(() => {
if (inView && onScroll) {
onScroll();
}
}, [inView])
const lastElement = useMemo(() => options.at(-1), [options]);
return (
<div className={optionSelectClasses}>
{!labelHidden && <div className="select__label">{label}</div>}
<div ref={optionSelect}>
<button
type="button"
onClick={() => toggleOpen(true)}
className={optionSelectButtonClasses}
>
{selectedElement
? selectedElement.label
: <span className="options-select__placeholder">{placeholder ?? 'Make a choice'}</span>}
<span className="select__icon">
<span className="Polaris-Icon Polaris-Icon--colorBase Polaris-Icon--applyColor">
<svg viewBox="0 0 20 20" className="Polaris-Icon__Svg" focusable="false" aria-hidden="true">
<path d="M7.676 9h4.648c.563 0 .879-.603.53-1.014L10.531 5.24a.708.708 0 0 0-1.062 0L7.145 7.986C6.798 8.397 7.113 9 7.676 9zm4.648 2H7.676c-.563 0-.878.603-.53 1.014l2.323 2.746c.27.32.792.32 1.062 0l2.323-2.746c.349-.411.033-1.014-.53-1.014z"></path>
</svg>
</span>
</span>
</button>
{open && (<div className="options-select">
<ul className="options-select__options options-select__space--y-1" >
{options.map((option: OptionProps) => {
const isSelected = option.value == value;
const isLastElement = option.label === lastElement?.label && option.value === lastElement.value;
const optionClasses = classNames('options-select__single-option', {
'options-select__single-option_select': isSelected,
'options-select__single-option_disabled': option.disabled
});
return (<li key={option.value} ref={isLastElement ? ref : null}>
<button
type="button"
className={optionClasses}
onClick={() => handleOnChange(option.value)}
>
{option.label}
</button>
</li>)
})}
</ul>
</div>)}
</div>
</div>
)
}
export default OptionSelect;