import { Select, Space, Input } from "antd";
import { LoadingOutlined, SearchOutlined } from "@ant-design/icons";
import React from "react";

// 自动搜索输入框（带防抖）
interface AutoSearchProps {
  onSearch: (value: string) => void;
  loading: boolean;
  placeholder?: string;
  delay?: number; // 防抖延迟毫秒
}

const AutoSearch: React.FC<AutoSearchProps> = ({
  onSearch,
  loading,
  placeholder,
  delay = 400,
}) => {
  const [value, setValue] = React.useState("");
  const timerRef = React.useRef<number | null>(null);

  const triggerSearch = React.useCallback(
    (val: string) => {
      onSearch?.(val.trim());
    },
    [onSearch]
  );

  React.useEffect(() => {
    if (timerRef.current) {
      clearTimeout(timerRef.current);
    }
    timerRef.current = window.setTimeout(() => {
      triggerSearch(value);
    }, delay);
    return () => {
      if (timerRef.current) {
        clearTimeout(timerRef.current);
      }
    };
  }, [value, delay, triggerSearch]);

  return (
    <Input
      allowClear
      value={value}
      onChange={(e) => setValue(e.target.value)}
      onPressEnter={() => triggerSearch(value)}
      placeholder={placeholder}
      suffix={loading ? <LoadingOutlined spin /> : <SearchOutlined />}
    />
  );
};

interface IFilterProps {
  searchLoading: boolean;
  onSearchChange: (value: string) => void;
}

const Filter: React.FC<IFilterProps> = ({
  searchLoading,
  onSearchChange,
}) => {
  return (
    <Space>
      <div className="w-[300px]">
        <AutoSearch
          onSearch={onSearchChange}
          loading={searchLoading}
          placeholder={"请输入关键字"}
        />
      </div>
    </Space>
  );
};

export default Filter;
