import React, { useState, useEffect, useRef } from "react"; import { useNavigate, useSearchParams } from "react-router-dom"; import styled from "styled-components"; // Styled components const SearchBox = styled.div` display: flex; align-items: center; padding: 5px; `; const SearchContainer = styled.div` position: relative; display: flex; align-items: center; flex-grow: 1; margin: 0px 10px; `; const Searchinput = styled.input` flex-grow: 1; border: none; border-radius: 25px; padding: 12px 40px; font-size: 16px; outline: none; background-color: white; border: 1px solid #ccc; transition: background-color 0.3s ease, border-color 0.3s ease; &:focus { background-color: lightgray; } `; const SearchIcon = styled.svg` position: absolute; left: 10px; fill: #888; width: 20px; height: 20px; pointer-events: none; `; export default function SearchInput({ shopId, tableCode, autofocus, onSearchChange, }) { const [songName, setSongName] = useState(""); const [debouncedSongName, setDebouncedSongName] = useState(""); const navigate = useNavigate(); const [searchParams, setSearchParams] = useSearchParams(); const inputRef = useRef(null); const [siteLoaded, setSiteLoaded] = useState(false); // Initialize the input field with the query parameter from the URL useEffect(() => { setTimeout(function () { setSiteLoaded(true); }, 5000); }, []); useEffect(() => { const query = searchParams.get("query") || ""; if (autofocus) setSongName(query); setSiteLoaded(true); }, [searchParams]); useEffect(() => { if (siteLoaded) { //Start the timer let url = ""; if (autofocus || songName != "") { url = tableCode ? `/${shopId}/${tableCode}/search?query=${encodeURIComponent( songName )}` : `/${shopId}/search?query=${encodeURIComponent(songName)}`; navigate(url); } if (autofocus) { if (songName == "") { if (tableCode) navigate(`/${shopId}/${tableCode}?find=true`); else navigate(`/${shopId}?find=true`); } } if (onSearchChange) onSearchChange(songName); } }, [songName]); const handleChange = (event) => { setSongName(event.target.value); }; // Navigate only when the debouncedSongName changes useEffect(() => {}, [debouncedSongName, navigate]); // Handle input change // Focus input when component mounts useEffect(() => { const isFinding = searchParams.get("find") || false; if (autofocus || isFinding) if (inputRef.current) inputRef.current.focus(); }, []); const handleBlur = () => { const isFinding = searchParams.get("find") || false; if (isFinding) { if (tableCode) navigate(`/${shopId}/${tableCode}`); else navigate(`/${shopId}`); } }; return ( ); }