import { __ } from "@wordpress/i18n"
import { Icon } from "@wordpress/icons"
import { search } from "@wordpress/icons"
import { useRef, useState, useEffect } from "@wordpress/element"
import useSearchStore from "@/stores/searchStore"
import usePluginSelectedStore from "@/stores/pluginSelectedStore"
import { useNavigate } from "@tanstack/react-router"
import useSearchModalStore from "@/stores/searchModalStore"

interface SearchInputProps {
    size?: 'small' | 'medium' | 'large'
}

const SearchInput = ({ size = 'medium' }: SearchInputProps) => {
    const { query, setQuery } = useSearchStore()
    const [localValue, setLocalValue] = useState('')
    const { setPlugin } = usePluginSelectedStore()
    const { open, setOpen } = useSearchModalStore()
    const navigate = useNavigate()
    const inputRef = useRef<HTMLInputElement>(null)

    // Focus input when modal opens
    useEffect(() => {
        if (open && inputRef.current) {
            inputRef.current.focus()
        }
    }, [open])

    const sizeClasses = {
        small: {
            container: 'py-1',
            input: '!text-sm p-1',
            button: 'p-1'
        },
        medium: {
            container: 'py-2 px-4',
            input: '!text-xl p-2',
            button: 'p-2'
        },
        large: {
            container: 'py-3 px-5',
            input: '!text-2xl p-3',
            button: 'p-3'
        }
    }

    const currentSize = sizeClasses[size]

    return (
        <div className="flex justify-center">
            <div className={`flex items-center shadow-md w-full border border-neutral-300 bg-white ${currentSize.container} rounded-lg`}>
                <form className="flex items-center w-full" onSubmit={(e) => {
                    e.preventDefault()
                    inputRef.current?.blur()
                    setPlugin(null)
                    setQuery(localValue)
                    setOpen(false)
                    navigate({ to: '/search' })
                }}>
                    <input ref={inputRef} type="text" className={`${currentSize.input} w-full rounded-lg !border-0 focus:!outline-none focus:!ring-0 focus:!border-0 focus:!shadow-none`} placeholder={__("Try \"I need to add forms to my site\"", "ploogins")} value={localValue} onChange={(e) => setLocalValue(e.target.value)} />
                    <button type="submit" className={`${currentSize.button} rounded-lg`}>
                        <Icon icon={search} />
                    </button>
                </form>
            </div>
        </div>
    )
}

export default SearchInput