import type { ReactNode } from 'react'

import { Field } from '@evobgp/ui/components/field'
import {
  InputGroup,
  InputGroupAddon,
  InputGroupButton,
  InputGroupInput,
} from '@evobgp/ui/components/input-group'
import { ListFilterIcon, SearchIcon, XIcon } from 'lucide-react'

import { panelCardInsetClassName } from '@/components/panel-card'
import { cn } from '@evobgp/ui/lib/utils'

interface DataGridToolbarProps {
  searchValue: string
  onSearchChange: (value: string) => void
  searchPlaceholder?: string
  /** ReUI Filters trigger or custom filter controls. Preview: https://reui.io/preview/base/data-grid-filtering-2 */
  filters?: ReactNode
  actions?: ReactNode
  className?: string
}

/** Search + optional ReUI Filters row for Frame data grids. */
export function DataGridToolbar({
  searchValue,
  onSearchChange,
  searchPlaceholder = 'Поиск…',
  filters,
  actions,
  className,
}: DataGridToolbarProps) {
  return (
    <div className={cn('flex flex-wrap items-center gap-3 border-b', panelCardInsetClassName, className)}>
      <Field className="min-w-[200px] flex-1">
        <InputGroup>
          <InputGroupAddon align="inline-start">
            <SearchIcon aria-hidden="true" />
          </InputGroupAddon>
          <InputGroupInput
            placeholder={searchPlaceholder}
            value={searchValue}
            onChange={(event) => onSearchChange(event.target.value)}
            aria-label={searchPlaceholder}
          />
          <InputGroupAddon align="inline-end" className="gap-1">
            {searchValue.length > 0 ? (
              <InputGroupButton
                aria-label="Очистить поиск"
                size="icon-xs"
                variant="ghost"
                onClick={() => onSearchChange('')}
              >
                <XIcon aria-hidden="true" />
              </InputGroupButton>
            ) : null}
            {filters ? (
              filters
            ) : (
              <InputGroupButton
                aria-label="Фильтры"
                size="icon-xs"
                variant="ghost"
                disabled
                title="Передайте filters={<Filters … />} из @/components/reui/filters"
              >
                <ListFilterIcon aria-hidden="true" />
              </InputGroupButton>
            )}
          </InputGroupAddon>
        </InputGroup>
      </Field>
      {actions ? <div className="flex shrink-0 flex-wrap items-center gap-2">{actions}</div> : null}
    </div>
  )
}
