"use client";
import { FC, useEffect, useState } from "react";
import { IoSearch } from "react-icons/io5";

type Props = {
  className?: string;
  defaultValue?: string;
  placeholder?: string;
  onChange?: (value: string) => void;
  debounce?: number;
  autoFocus?: boolean;
};

export const SearchInput: FC<Props> = ({
  className = "",
  defaultValue = "",
  placeholder = "Search",
  onChange,
  debounce = 500,
  autoFocus = false,
}) => {
  const [value, setValue] = useState(defaultValue);

  useEffect(() => {
    const timer = setTimeout(() => {
      onChange?.(value ?? "");
    }, debounce);

    return () => clearTimeout(timer);
  }, [value]);

  return (
    <div className={`relative text-gray-600 inline-block ${className}`}>
      <input
        type="search"
        name="serch"
        className="bg-white h-10 px-5 pr-10 rounded-full text-sm focus:outline-none w-48 focus:w-[400px] transition-all"
        value={value}
        placeholder={placeholder}
        onChange={(e) => setValue(e.target.value)}
        autoFocus={autoFocus}
      />
      <button type="submit" className="absolute right-0 top-0 mt-3 mr-4">
        <IoSearch />
      </button>
    </div>
  );
};
