import { type RefObject } from "react";
import { Search, X } from "lucide-react";

type ComponentSearchBarProps = {
  value: string;
  onChange: (value: string) => void;
  totalCount: number;
  filteredCount: number;
  inputRef?: RefObject<HTMLInputElement | null>;
  id?: string;
};

export default function ComponentSearchBar({
  value,
  onChange,
  totalCount,
  filteredCount,
  inputRef,
  id = "component-module-search",
}: ComponentSearchBarProps) {
  const hasActiveSearch = value.trim().length > 0;

  return (
    <div
      style={{
        marginBottom: 20,
        padding: 16,
        background: "#f8fafc",
        borderRadius: 12,
        border: "1px solid #e2e8f0",
      }}
    >
      <label htmlFor={id} style={{ display: "block", fontSize: 13, fontWeight: 600, color: "#374151", marginBottom: 8 }}>
        Search components
      </label>
      <div style={{ position: "relative" }}>
        <Search size={18} style={{ position: "absolute", left: 14, top: "50%", transform: "translateY(-50%)", color: "#94a3b8", pointerEvents: "none" }} />
        <input
          ref={inputRef}
          id={id}
          type="search"
          value={value}
          onChange={(e) => onChange(e.target.value)}
          placeholder="Search by component name (e.g. hero, skill)..."
          aria-label="Search components by name"
          autoComplete="off"
          style={{
            width: "100%",
            padding: hasActiveSearch ? "11px 40px 11px 42px" : "11px 14px 11px 42px",
            border: "1px solid #cbd5e1",
            borderRadius: 12,
            fontSize: 15,
            boxSizing: "border-box",
            background: "#fff",
            outline: "none",
          }}
        />
        {hasActiveSearch && (
          <button
            type="button"
            onClick={() => {
              onChange("");
              inputRef?.current?.focus();
            }}
            aria-label="Clear search"
            style={{
              position: "absolute",
              right: 10,
              top: "50%",
              transform: "translateY(-50%)",
              padding: 4,
              border: "none",
              background: "transparent",
              cursor: "pointer",
              color: "#94a3b8",
              display: "flex",
              alignItems: "center",
            }}
          >
            <X size={18} />
          </button>
        )}
      </div>
      <p aria-live="polite" style={{ margin: "8px 0 0", fontSize: 13, color: "#64748b" }}>
        {hasActiveSearch
          ? `${filteredCount} of ${totalCount} component${totalCount === 1 ? "" : "s"} shown`
          : `${totalCount} component${totalCount === 1 ? "" : "s"} available`}
      </p>
    </div>
  );
}
