"use client";

import * as React from "react";
import { SearchIcon, XIcon } from "lucide-react";

import {
  InputGroup,
  InputGroupAddon,
  InputGroupButton,
  InputGroupInput,
  InputGroupText,
} from "@/components/ui/input-group";
import { useTranslation } from "@/hooks/useTranslation";
import { cn } from "@/lib/utils";

interface DataTableSearchProps {
  value: string;
  /** Fires debounced (300ms) on typing, immediately on clear */
  onChange: (value: string) => void;
  placeholder?: string;
  className?: string;
}

const DEBOUNCE_MS = 300;

/** Debounced, clearable search box used in the DataTable toolbar. */
function DataTableSearch({
  value,
  onChange,
  placeholder,
  className,
}: DataTableSearchProps) {
  const { t } = useTranslation();
  const [text, setText] = React.useState(value);

  // Sync down external resets (e.g. parent clears filters) — render-phase
  // derived-state pattern, not an effect
  const [prevValue, setPrevValue] = React.useState(value);
  if (prevValue !== value) {
    setPrevValue(value);
    setText(value);
  }

  // Keep the latest callback without retriggering the debounce effect
  const onChangeRef = React.useRef(onChange);
  React.useEffect(() => {
    onChangeRef.current = onChange;
  });

  React.useEffect(() => {
    if (text === value) return;
    const id = setTimeout(() => onChangeRef.current(text), DEBOUNCE_MS);
    return () => clearTimeout(id);
  }, [text, value]);

  function handleClear() {
    setText("");
    onChangeRef.current("");
  }

  return (
    <InputGroup className={cn("w-full sm:max-w-xs", className)}>
      <InputGroupAddon align="inline-start">
        <InputGroupText>
          <SearchIcon className="size-4 text-muted-foreground" />
        </InputGroupText>
      </InputGroupAddon>
      <InputGroupInput
        type="text"
        value={text}
        placeholder={placeholder ?? t("dataTable.searchPlaceholder")}
        aria-label={placeholder ?? t("dataTable.searchPlaceholder")}
        onChange={(event) => setText(event.target.value)}
      />
      {text !== "" && (
        <InputGroupAddon align="inline-end">
          <InputGroupButton
            size="icon-xs"
            aria-label={t("common.cancel")}
            onClick={handleClear}
          >
            <XIcon className="size-4 text-muted-foreground" />
          </InputGroupButton>
        </InputGroupAddon>
      )}
    </InputGroup>
  );
}

export { DataTableSearch };
