import React, { useState, useEffect } from 'react';
import { Search, X } from 'lucide-react';

export interface SettingsSearchProps {
  placeholder?: string;
  onSearch: (query: string) => void;
  className?: string;
}

const SettingsSearch: React.FC<SettingsSearchProps> = ({
  placeholder = 'Search settings...',
  onSearch,
  className = '',
}) => {
  const [query, setQuery] = useState('');

  useEffect(() => {
    const debounceTimer = setTimeout(() => {
      onSearch(query);
    }, 300);

    return () => clearTimeout(debounceTimer);
  }, [query, onSearch]);

  const handleClear = () => {
    setQuery('');
    onSearch('');
  };

  return (
    <div className={`relative ${className}`}>
      <div className="relative">
        <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-[var(--text-tertiary)]" />
        <input
          type="text"
          value={query}
          onChange={(e) => setQuery(e.target.value)}
          placeholder={placeholder}
          className="w-full pl-10 pr-10 py-2.5 border border-[var(--border-primary)] rounded-lg bg-[var(--bg-primary)] text-[var(--text-primary)] placeholder-[var(--text-tertiary)] focus:ring-2 focus:ring-[var(--color-primary)] focus:border-transparent transition-all"
        />
        {query && (
          <button
            onClick={handleClear}
            className="absolute right-3 top-1/2 transform -translate-y-1/2 text-[var(--text-tertiary)] hover:text-[var(--text-primary)] transition-colors"
            aria-label="Clear search"
          >
            <X className="w-5 h-5" />
          </button>
        )}
      </div>

      {query && (
        <div className="absolute top-full left-0 right-0 mt-2 p-2 bg-[var(--bg-secondary)] border border-[var(--border-primary)] rounded-lg shadow-lg z-10">
          <p className="text-xs text-[var(--text-secondary)]">
            Searching for: <span className="font-semibold text-[var(--text-primary)]">"{query}"</span>
          </p>
        </div>
      )}
    </div>
  );
};

export default SettingsSearch;
