import { useState, useEffect } from 'react';
import { Input } from './Input';
import { defaultLayoutConfig, type LayoutConfig } from '~/lib/layout-utils';

interface SearchInputProps {
  placeholder?: string;
  onSearch: (query: string) => void;
  debounceMs?: number;
  className?: string;
  config?: Partial<LayoutConfig>;
  initialValue?: string;
}

export function SearchInput({
  placeholder = "البحث...",
  onSearch,
  debounceMs = 300,
  className = '',
  config = {},
  initialValue = '',
}: SearchInputProps) {
  const layoutConfig = { ...defaultLayoutConfig, ...config };
  const [query, setQuery] = useState(initialValue);

  useEffect(() => {
    const timer = setTimeout(() => {
      onSearch(query);
    }, debounceMs);

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

  return (
    <div className={`relative ${className}`} dir={layoutConfig.direction}>
      <div className="absolute inset-y-0 right-0 pr-3 flex items-center pointer-events-none">
        <svg
          className="h-5 w-5 text-gray-400"
          fill="none"
          stroke="currentColor"
          viewBox="0 0 24 24"
        >
          <path
            strokeLinecap="round"
            strokeLinejoin="round"
            strokeWidth={2}
            d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
          />
        </svg>
      </div>
      <Input
        type="text"
        placeholder={placeholder}
        value={query}
        onChange={(e) => setQuery(e.target.value)}
        className="pr-10"
      />
      {query && (
        <button
          onClick={() => setQuery('')}
          className="absolute inset-y-0 left-0 pl-3 flex items-center"
        >
          <svg
            className="h-5 w-5 text-gray-400 hover:text-gray-600"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M6 18L18 6M6 6l12 12"
            />
          </svg>
        </button>
      )}
    </div>
  );
}