"use client";
import { Button } from "@suphark/ui/components/shared/button/button";
import { NativeSelect, NativeSelectOption } from "@suphark/ui/components/ui/native-select";
import { cn } from "@suphark/ui/lib/utils";
import { XIcon } from "lucide-react";
import type { ReactNode } from "react";
import { SearchInput } from "./form/search-input";
import { useUiText } from "./ui-text";
export interface FilterBarFilter {
id: string;
/** aria-label ของ select (ไม่มี label ที่มองเห็น) */
label: string;
value: string;
onValueChange: (value: string) => void;
options: ReadonlyArray<{ value: string; label: string }>;
/** ค่าที่หมายถึง "ทั้งหมด" (ไม่กรอง) — ใช้ตัดสินว่ามีตัวกรองค้างไหม และค่าที่ปุ่มล้างตั้งกลับ (ค่าเริ่มต้น "") */
allValue?: string;
className?: string;
}
/**
* แถบค้นหา + ตัวกรองเหนือตาราง/รายการแบบ client-side (ยกจาก Pi Auth — มี 14 หน้าเขียนซ้ำ):
* ช่องค้นหาซ้าย · select ตัวกรองขวา · ปุ่ม "ล้างตัวกรอง" โผล่เมื่อมีอะไรค้าง
* ตารางที่ใช้ tanstack ให้ใช้ toolbar ของ `@suphark/ui/data-table` แทน
*
*
*/
export function FilterBar({
search,
filters = [],
onClear,
active,
children,
className,
}: {
search?: { value: string; onValueChange: (value: string) => void; placeholder?: string };
filters?: FilterBarFilter[];
/** ไม่ส่ง = ล้างช่องค้นหา + ตั้งทุกตัวกรองกลับ `allValue` ให้เอง */
onClear?: () => void;
/** บังคับสถานะ "มีตัวกรองค้าง" (เช่นมีตัวกรองใน children) — ไม่ส่ง = คำนวณจาก search/filters */
active?: boolean;
/** ตัวกรองแบบอื่นที่แอปประกอบเอง (DateRangePicker, ToggleGroup …) วางต่อจาก select */
children?: ReactNode;
className?: string;
}) {
const text = useUiText();
const isActive =
active ?? ((search?.value ?? "") !== "" || filters.some((f) => f.value !== (f.allValue ?? "")));
const clear = () => {
if (onClear) return onClear();
search?.onValueChange("");
for (const f of filters) f.onValueChange(f.allValue ?? "");
};
return (
{search && (
)}
{(filters.length > 0 || children || isActive) && (
{filters.map((f) => (
f.onValueChange(e.target.value)}
className={cn("w-auto max-w-48", f.className)}
>
{f.options.map((o) => (
{o.label}
))}
))}
{children}
{isActive && (
)}
)}
);
}