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

interface CompanyFiltersPanelProps {
  filters: CompanyFilters;
  onFiltersChange: (filters: CompanyFilters) => void;
}

export function CompanyFiltersPanel({ filters, onFiltersChange }: CompanyFiltersPanelProps) {
  const [searchTerm, setSearchTerm] = useState(filters.search || '');
  const [showFilters, setShowFilters] = useState(false);
  const { companies } = useCompanies({ limit: 100 });

  const debouncedSearch = useDebounce(searchTerm, 300);

  const handleSearchChange = (value: string) => {
    setSearchTerm(value);
  };

  // Update filters when debounced search changes
  if (debouncedSearch !== filters.search) {
    onFiltersChange({ ...filters, search: debouncedSearch, page: 1 });
  }

  // Get parent companies (those that can be parents)
  const parentOptions = [
    { value: '', label: 'Todas las empresas' },
    ...companies
      .filter((c) => !c.parentCompanyId) // Only root companies as filter options
      .map((c) => ({ value: c.id, label: c.name })),
  ];

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

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

  const hasActiveFilters = filters.search || filters.parentCompanyId;

  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 RFC..."
            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-64">
            <label className="mb-1 block text-sm font-medium text-gray-700">
              Empresa matriz
            </label>
            <Select
              options={parentOptions}
              value={filters.parentCompanyId || ''}
              onChange={handleParentChange}
              placeholder="Seleccionar..."
            />
          </div>
        </div>
      )}
    </div>
  );
}
