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;
  stateValue: any;
  onSelectChange: (value: any) => void;
  onSearchChange: (value: string) => void;
}

const Filter: React.FC<IFilterProps> = ({
  searchLoading,
  stateValue,
  onSelectChange,
  onSearchChange,
}) => {
  return (
    <Space>
      <div>
        <span className="text-base">状态</span>
        <Select
          className="mx-3 w-32"
          value={stateValue}
          defaultValue={""}
          onChange={(val) => {
            onSelectChange(val);
          }}
          options={[
            { value: "", label: "全部" },
            { value: true, label: "在线" },
            { value: false, label: "离线" },
          ]}
        />
      </div>
      <div className="w-[400px]">
        <AutoSearch
          onSearch={onSearchChange}
          loading={searchLoading}
          placeholder={"请输入国标编号或通道名称"}
        />
      </div>
    </Space>
  );
};

export default Filter;
