"use client";

import { type InputHTMLAttributes, type KeyboardEvent } from "react";
import { IconSearch } from "./icons";

const inputClassName =
  "text-m-regular h-10 w-full rounded-lg border border-neutral-40 bg-neutral-10 px-[22px] py-2 pr-10 text-neutral-100 placeholder:text-neutral-70 outline-none focus:border-primary-500 disabled:cursor-not-allowed disabled:opacity-60";

export type FilterSearchInputProps = Omit<
  InputHTMLAttributes<HTMLInputElement>,
  "value" | "onChange" | "type" | "className"
> & {
  value: string;
  onChange: (value: string) => void;
  onSearch?: (value: string) => void;
  className?: string;
  searchButtonLabel?: string;
};

export function FilterSearchInput({
  value,
  onChange,
  onSearch,
  placeholder = "Cari...",
  className,
  disabled,
  searchButtonLabel = "Cari",
  ...inputProps
}: FilterSearchInputProps) {
  function triggerSearch() {
    if (disabled) return;
    (onSearch ?? onChange)(value);
  }

  function handleKeyDown(event: KeyboardEvent<HTMLInputElement>) {
    if (event.key === "Enter") {
      event.preventDefault();
      triggerSearch();
    }
  }

  return (
    <div
      className={[
        "relative min-w-[180px] flex-1 max-w-[220px]",
        className,
      ]
        .filter(Boolean)
        .join(" ")}
    >
      <input
        type="search"
        value={value}
        onChange={(event) => onChange(event.target.value)}
        onKeyDown={handleKeyDown}
        placeholder={placeholder}
        disabled={disabled}
        className={inputClassName}
        {...inputProps}
      />
      <button
        type="button"
        onClick={triggerSearch}
        className="absolute top-1/2 right-[22px] -translate-y-1/2 text-neutral-70 transition-colors hover:text-neutral-100 disabled:cursor-not-allowed disabled:opacity-60"
        aria-label={searchButtonLabel}
        disabled={disabled}
      >
        <IconSearch className="size-5" />
      </button>
    </div>
  );
}
