import { useState, useEffect } from 'react'
import { Input } from '@/components/ui/input'
import { useDebouncedValue } from '@/hooks/useDebouncedValue'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'

interface UsersFiltersProps {
  onRolChange: (rol: string) => void
  onActivoChange: (activo: boolean | undefined) => void
  /** Called with the debounced search string (300ms) */
  onSearchChange: (search: string) => void
}

const ROL_OPTIONS = [
  { value: '', label: 'Todos los roles' },
  { value: 'admin', label: 'Admin' },
  { value: 'cajero', label: 'Cajero' },
  { value: 'reportes', label: 'Reportes' },
]

export function UsersFilters({ onRolChange, onActivoChange, onSearchChange }: UsersFiltersProps) {
  const [searchRaw, setSearchRaw] = useState('')
  const debouncedSearch = useDebouncedValue(searchRaw, 300)

  // Propagate debounced search to parent
  useEffect(() => {
    onSearchChange(debouncedSearch)
  }, [debouncedSearch, onSearchChange])

  return (
    <div className="flex flex-wrap gap-3 items-center mb-4">
      {/* Search input */}
      <Input
        type="text"
        placeholder="Buscar por usuario, nombre, email..."
        value={searchRaw}
        onChange={(e) => setSearchRaw(e.target.value)}
        className="max-w-xs"
        aria-label="Buscar usuarios"
      />

      {/* Rol select */}
      <Select
        defaultValue="__all__"
        onValueChange={(v) => onRolChange(v === '__all__' ? '' : v)}
      >
        <SelectTrigger className="h-9 w-40" aria-label="Rol">
          <SelectValue placeholder="Todos los roles" />
        </SelectTrigger>
        <SelectContent>
          {ROL_OPTIONS.map((r) => (
            <SelectItem key={r.value || '__all__'} value={r.value || '__all__'}>
              {r.label}
            </SelectItem>
          ))}
        </SelectContent>
      </Select>

      {/* Activo filter */}
      <Select
        defaultValue="__all__"
        onValueChange={(v) => {
          if (v === '__all__') onActivoChange(undefined)
          else onActivoChange(v === 'true')
        }}
      >
        <SelectTrigger className="h-9 w-32" aria-label="Estado">
          <SelectValue placeholder="Todos" />
        </SelectTrigger>
        <SelectContent>
          <SelectItem value="__all__">Todos</SelectItem>
          <SelectItem value="true">Activos</SelectItem>
          <SelectItem value="false">Inactivos</SelectItem>
        </SelectContent>
      </Select>
    </div>
  )
}
