import { useState } from "react"
import { IconButton, Input, useMediaQuery, useTheme } from "@mui/material"
import Trash from "@/assets/icons/trash"
import { useDebouncedCallback } from "use-debounce"

interface Props {
    isError: boolean
    constrictor: (text: string) => void
}

export const DataConstrictor = ({
    isError,
    constrictor,

}: Props) => {
    const theme = useTheme();
    const isMobile = useMediaQuery(theme.breakpoints.down(600));

    const [text, setText] = useState("")
    const errCalc = isError && text.length > 0

    const debouncedTestHC = useDebouncedCallback(
        (value: string) => {
            constrictor(value)
        },
        700
    );

    return <Input
        value={text}
        placeholder="быстрый поиск"
        disableUnderline
        sx={{
            bgcolor: isError ? "#e6bbbb" : "#f2f3f7",
            borderRadius: "10px",
            maxWidth: isMobile ? "200px" : "300px",
            p: "0 5px 0 15px",
            mt: "10px",
            "&:hover": {
                bgcolor: errCalc ? "#e6bbbb" : "#ececec"
            }
        }}
        endAdornment={
            text.length > 0
                ?
                <IconButton
                    onClick={() => {
                        setText("")
                        constrictor("")
                    }}
                >
                    <Trash />
                </IconButton>
                :
                null
        }
        onChange={({ target }) => {
            setText(target.value)
            debouncedTestHC(target.value)
        }}
    />
}