import { useState } from 'react';
import { Search, Filter, X } from 'lucide-react';
import { Button } from '@components/atoms/Button';
import { Select } from '@components/organisms/Select';
import { useRoles } from '../hooks';
import { useDebounce } from '@hooks/useDebounce';
import type { UserFilters, UserStatus } from '../types';

interface UserFiltersPanelProps {
  filters: UserFilters;
  onFiltersChange: (filters: UserFilters) => void;
}

const statusOptions = [
  { value: '', label: 'Todos los estados' },
  { value: 'active', label: 'Activo' },
  { value: 'inactive', label: 'Inactivo' },
  { value: 'pending', label: 'Pendiente' },
  { value: 'suspended', label: 'Suspendido' },
];

export function UserFiltersPanel({ filters, onFiltersChange }: UserFiltersPanelProps) {
  const [searchTerm, setSearchTerm] = useState(filters.search || '');
  const [showFilters, setShowFilters] = useState(false);
  const { roles } = useRoles();

  const debouncedSearch = useDebounce(searchTerm, 300);

  // Update filters when debounced search changes
  const handleSearchChange = (value: string) => {
    setSearchTerm(value);
  };

  // Effect handled by parent through debouncedSearch
  if (debouncedSearch !== filters.search) {
    onFiltersChange({ ...filters, search: debouncedSearch, page: 1 });
  }

  const roleOptions = [
    { value: '', label: 'Todos los roles' },
    ...roles.map((role) => ({ value: role.id, label: role.name })),
  ];

  const handleStatusChange = (value: string | string[]) => {
    onFiltersChange({
      ...filters,
      status: (value as UserStatus) || undefined,
      page: 1
    });
  };

  const handleRoleChange = (value: string | string[]) => {
    onFiltersChange({
      ...filters,
      roleId: (value as string) || undefined,
      page: 1
    });
  };

  const clearFilters = () => {
    setSearchTerm('');
    onFiltersChange({ page: 1, limit: filters.limit });
  };

  const hasActiveFilters = filters.search || filters.status || filters.roleId;

  return (
    <div className="space-y-4">
      <div className="flex items-center gap-3">
        {/* Search */}
        <div className="relative flex-1">
          <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" />
          <input
            type="text"
            value={searchTerm}
            onChange={(e) => handleSearchChange(e.target.value)}
            placeholder="Buscar por nombre o email..."
            className="w-full rounded-lg border border-gray-300 py-2 pl-10 pr-4 focus:border-primary-500 focus:outline-none focus:ring-1 focus:ring-primary-500"
          />
        </div>

        {/* Toggle filters */}
        <Button
          variant={showFilters ? 'secondary' : 'outline'}
          onClick={() => setShowFilters(!showFilters)}
        >
          <Filter className="mr-2 h-4 w-4" />
          Filtros
        </Button>

        {/* Clear filters */}
        {hasActiveFilters && (
          <Button variant="ghost" onClick={clearFilters}>
            <X className="mr-2 h-4 w-4" />
            Limpiar
          </Button>
        )}
      </div>

      {/* Expanded filters */}
      {showFilters && (
        <div className="flex flex-wrap gap-4 rounded-lg border bg-gray-50 p-4">
          <div className="w-48">
            <label className="mb-1 block text-sm font-medium text-gray-700">
              Estado
            </label>
            <Select
              options={statusOptions}
              value={filters.status || ''}
              onChange={handleStatusChange}
              placeholder="Seleccionar..."
            />
          </div>

          <div className="w-48">
            <label className="mb-1 block text-sm font-medium text-gray-700">
              Rol
            </label>
            <Select
              options={roleOptions}
              value={filters.roleId || ''}
              onChange={handleRoleChange}
              placeholder="Seleccionar..."
            />
          </div>
        </div>
      )}
    </div>
  );
}
