import React, { useRef, useEffect, useState } from 'react' import { useDebounce } from '@/hooks' import { usePage } from '@inertiajs/react' import axios from 'axios' import { HiChevronDown, HiChevronUp, HiX } from 'react-icons/hi' import { Spinner } from 'flowbite-react' export default function SelectionInput(props) { const ref = useRef() const { props: { auth }, } = usePage() const { label = '', itemSelected = null, onItemSelected = () => {}, disabled = false, placeholder = '', error = '', all = 0, } = props const [showItems, setShowItem] = useState([]) const [isSelected, setIsSelected] = useState(true) const [selected, setSelected] = useState(null) const [query, setQuery] = useState('') const q = useDebounce(query, 300) const [isOpen, setIsOpen] = useState(false) const [loading, setLoading] = useState(false) const toggle = () => { setQuery('') setIsOpen(!isOpen) } const onInputMouseDown = () => { setIsSelected(false) setQuery('') setIsOpen(!isOpen) } const handleSelectItem = (item) => { setIsSelected(true) onItemSelected(item.id) setSelected(item.name) setIsOpen(false) } const removeItem = () => { setIsSelected(false) setSelected('') onItemSelected(null) } const filterItems = (value) => { setIsSelected(false) setQuery(value) } useEffect(() => { if (isOpen === true) { const checkIfClickedOutside = (e) => { if (isOpen && ref.current && !ref.current.contains(e.target)) { setIsOpen(false) if (selected !== null) { setIsSelected(true) } } } document.addEventListener('mousedown', checkIfClickedOutside) return () => { document.removeEventListener('mousedown', checkIfClickedOutside) } } }, [isOpen]) const fetch = (q = '') => { setLoading(true) axios .get(route('api.customer.index', { q: q, all: all }), { headers: { 'Content-Type': 'application/json', Authorization: 'Bearer ' + auth.user.jwt_token, }, }) .then((response) => { setShowItem(response.data) }) .catch((err) => { alert(err) }) .finally(() => setLoading(false)) } // every select item open useEffect(() => { if (isOpen) { fetch(q) } }, [q, isOpen]) // once page load useEffect(() => { fetch() }, []) useEffect(() => { if (disabled) { setSelected('') } }, [disabled]) useEffect(() => { if (itemSelected !== null) { const item = showItems.find((item) => item.id === itemSelected) if (item) { setSelected(item.name) setIsSelected(true) } return } setIsSelected(false) }, [itemSelected, loading]) useEffect(() => { if (isSelected && selected === '') { setSelected('') setIsSelected(false) } }, [isSelected]) return (
{label !== '' && ( )}
filterItems(e.target.value) } disabled={disabled} /> {isSelected && (
{} : removeItem } >
)}
{} : toggle}>
{error && (

{error}

)}
{isOpen && (
{loading ? (
Loading...
) : ( <> {showItems.map((item, index) => (
handleSelectItem(item) } >
{item.name}
))} {showItems.length <= 0 && (
No Items Found
)} )}
)}
) }