import { useState } from "react";

/**
 * Custom search field component including a clear search functionality
 */
type SearchFieldProps = { 
    onSearchStringChanged: (searchString : string) => void
}

/**
 * @param SearchFieldProps consisting of an initial searchString and an onSearchStringChanged handler
 * @returns Custom search field component
 */
export default function SearchField({onSearchStringChanged} : SearchFieldProps){
    const [currentSearchString, setCurrentSearchString] = useState<string>("")
    
    const changeSearchString = (newSearchString : string) => {
        console.log(newSearchString);
        setCurrentSearchString(newSearchString);
        onSearchStringChanged(newSearchString)
    }

    return (
        <div className="relative">
        {/* Input of searchfield
            Defines border and behavior. Requires extra padding at both sides to
            accomodate the icons
         */}
        <input
            className="input-field pl-10 pr-10"
            type="text"
            placeholder="Search"
            value={currentSearchString}
            onChange={ e => changeSearchString(e.target.value) }
        />
        {/* Right icon: X 
            Clears search string on click
          */}
        <button 
            className="absolute right-0 inset-y-0 flex items-center"
            onClick = { () => changeSearchString("") }
        >
            <svg
            xmlns="http://www.w3.org/2000/svg"
            className="-ml-1 mr-3 h-6 w-6 text-gray-400 hover:text-gray-500"
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
            >
            <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth="2"
                d="M6 18L18 6M6 6l12 12"
            />
            </svg>
        </button>
        {/* Left icon: Looking glass */}
        <div className="absolute left-0 inset-y-0 flex items-center">
            <svg
            xmlns="http://www.w3.org/2000/svg"
            className="ml-3 h-6 w-6 text-gray-400 hover:text-gray-500"
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
            >
            <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth="2"
                d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
            />
            </svg>
        </div>
    </div>
    )
}
