"use client"

import { ReactNode } from "react"
import { SearchIcon } from "lucide-react"
import { cn } from "@/lib/utils"
import {
  InputGroup,
  InputGroupAddon,
  InputGroupInput,
} from "@/components/ui/input-group"
import {
  Filters,
  type Filter,
  type FilterFieldConfig,
} from "@/components/reui/filters"
import { SegmentedControl } from "@/components/form-kit"
import { DATA_PAGE_TOOLBAR_CLASS } from "@/components/data-grids/shared/data-grid-layout"

function DataPageToolbarFrame({
  children,
  className,
}: {
  children: ReactNode
  className?: string
}) {
  return (
    <div className={cn(DATA_PAGE_TOOLBAR_CLASS, className)}>
      {children}
    </div>
  )
}

interface DataPageToolbarProps<T extends string = string> {
  search?: string
  onSearchChange?: (value: string) => void
  searchPlaceholder?: string
  segmented?: {
    value: T
    onChange: (value: T) => void
    options: { value: T; label: string; count?: number }[]
  }
  filters?: Filter[]
  onFiltersChange?: (filters: Filter[]) => void
  filterFields?: FilterFieldConfig[]
  countLabel?: string
  actions?: ReactNode
  className?: string
}

function DataPageToolbar<T extends string = string>({
  search,
  onSearchChange,
  searchPlaceholder = "Поиск…",
  segmented,
  filters,
  onFiltersChange,
  filterFields,
  countLabel,
  actions,
  className,
}: DataPageToolbarProps<T>) {
  return (
    <DataPageToolbarFrame className={className}>
      {segmented && (
        <SegmentedControl
          value={segmented.value}
          onChange={segmented.onChange}
          options={segmented.options}
        />
      )}
      {filterFields && filters && onFiltersChange && (
        <Filters
          filters={filters}
          fields={filterFields}
          onChange={onFiltersChange}
          size="sm"
        />
      )}
      {onSearchChange != null && (
        <InputGroup className="min-w-[220px] max-w-sm">
          <InputGroupAddon>
            <SearchIcon className="size-3.5" />
          </InputGroupAddon>
          <InputGroupInput
            placeholder={searchPlaceholder}
            value={search ?? ""}
            onChange={(e) => onSearchChange(e.target.value)}
          />
        </InputGroup>
      )}
      {countLabel && (
        <span className="text-sm text-muted-foreground ml-auto">{countLabel}</span>
      )}
      {actions}
    </DataPageToolbarFrame>
  )
}

export { DataPageToolbar, DataPageToolbarFrame, type DataPageToolbarProps }
