"use client";

import { useEffect, useRef, useState } from "react";
import { Search, X } from "lucide-react";
import { Input } from "@/components/ui/input";
import { useI18n } from "@/i18n";

/**
 * Debounced search input. The value shown updates instantly; the query only
 * propagates once the user stops typing, so the APIs are not hammered per key.
 */
export function DebouncedSearch({
  value,
  onChange,
  placeholder,
  className,
  ariaLabel,
}: {
  value: string;
  onChange: (value: string) => void;
  placeholder?: string;
  className?: string;
  ariaLabel?: string;
}) {
  const [inner, setInner] = useState(value);
  const [prevValue, setPrevValue] = useState(value);
  const timer = useRef<number | null>(null);
  const { dir } = useI18n();

  // Mirror an externally-driven value change (new search from URL state).
  if (prevValue !== value) {
    setPrevValue(value);
    setInner(value);
  }

  useEffect(() => {
    return () => {
      if (timer.current !== null) window.clearTimeout(timer.current);
    };
  }, []);

  function handleChange(next: string) {
    setInner(next);
    if (timer.current !== null) window.clearTimeout(timer.current);
    timer.current = window.setTimeout(() => onChange(next), 350);
  }

  return (
    <div className={className}>
      <div className="relative">
        <Search
          className="pointer-events-none absolute start-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"
          aria-hidden
        />
        <Input
          value={inner}
          onChange={(event) => handleChange(event.target.value)}
          placeholder={placeholder}
          aria-label={ariaLabel ?? placeholder}
          className="ps-9 pe-8"
          dir={dir}
        />
        {inner ? (
          <button
            type="button"
            onClick={() => handleChange("")}
            className="absolute end-2 top-1/2 -translate-y-1/2 rounded p-1 text-muted-foreground transition-colors hover:text-foreground"
            aria-label="Clear search"
          >
            <X className="h-3.5 w-3.5" aria-hidden />
          </button>
        ) : null}
      </div>
    </div>
  );
}