import { InputHTMLAttributes, forwardRef } from 'react';
import { cn } from '../lib/cn';

export interface SearchBarProps
  extends Omit<InputHTMLAttributes<HTMLInputElement>, 'onChange' | 'value'> {
  value?: string;
  onChange?: (value: string) => void;
  onClear?: () => void;
  placeholder?: string;
}

export const SearchBar = forwardRef<HTMLInputElement, SearchBarProps>(function SearchBar(
  { value = '', onChange, onClear, placeholder = 'Search…', className, disabled, ...rest },
  ref,
) {
  const hasValue = value.length > 0;
  return (
    <div
      className={cn(
        'flex items-center gap-2 h-9 px-3 rounded-lg bg-surface border border-border focus-within:border-primary focus-within:ring-2 focus-within:ring-primary-ring transition-colors',
        disabled && 'opacity-60 cursor-not-allowed',
        className,
      )}
    >
      <svg
        width="14"
        height="14"
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        strokeWidth="2"
        className="shrink-0 text-text-3"
        aria-hidden="true"
      >
        <circle cx="11" cy="11" r="8" />
        <line x1="21" y1="21" x2="16.65" y2="16.65" />
      </svg>
      <input
        ref={ref}
        type="search"
        value={value}
        onChange={(e) => onChange?.(e.target.value)}
        placeholder={placeholder}
        disabled={disabled}
        className="flex-1 bg-transparent outline-none text-sm text-text placeholder:text-text-3"
        {...rest}
      />
      {hasValue && !disabled && (
        <button
          type="button"
          aria-label="Clear search"
          onClick={() => {
            onChange?.('');
            onClear?.();
          }}
          className="shrink-0 inline-flex items-center justify-center w-5 h-5 rounded-full bg-surface-2 text-text-3 hover:text-text transition-colors"
        >
          <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3">
            <line x1="18" y1="6" x2="6" y2="18" />
            <line x1="6" y1="6" x2="18" y2="18" />
          </svg>
        </button>
      )}
    </div>
  );
});
