"use client";

import { useMemo, useState } from "react";
import { Search } from "lucide-react";
import { Input } from "@/components/ui/input";

export type SelectOption = {
  value: string;
  label: string;
  keywords?: string;
};

export function SearchableSelect({
  name,
  options,
  placeholder = "اختر السجل",
  searchPlaceholder = "ابحث بالاسم أو رقم الحالة",
  required = false,
  defaultValue = ""
}: {
  name: string;
  options: SelectOption[];
  placeholder?: string;
  searchPlaceholder?: string;
  required?: boolean;
  defaultValue?: string;
}) {
  const [query, setQuery] = useState("");
  const filtered = useMemo(() => {
    const normalized = query.trim().toLocaleLowerCase("ar");
    if (!normalized) return options;
    return options.filter((option) =>
      `${option.label} ${option.keywords ?? ""}`.toLocaleLowerCase("ar").includes(normalized)
    );
  }, [options, query]);

  return (
    <div className="grid gap-2">
      {options.length > 8 ? (
        <div className="relative">
          <Search size={16} className="absolute right-3 top-3.5 text-[var(--ink-faint)]" aria-hidden />
          <Input
            type="search"
            value={query}
            onChange={(event) => setQuery(event.target.value)}
            placeholder={searchPlaceholder}
            className="pr-9"
          />
        </div>
      ) : null}
      <select
        name={name}
        required={required}
        defaultValue={defaultValue}
        className="h-11 w-full min-w-0 rounded-md border bg-white px-3 text-sm"
      >
        <option value="">{placeholder}</option>
        {filtered.map((option) => (
          <option key={option.value} value={option.value} title={option.label}>
            {option.label}
          </option>
        ))}
      </select>
      {query && filtered.length === 0 ? (
        <p className="text-xs font-semibold text-[var(--ink-faint)]">لا توجد نتائج مطابقة.</p>
      ) : null}
    </div>
  );
}
