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 type { PartnerFilters, PartnerType } from '../types';

interface PartnerFiltersPanelProps {
  filters: PartnerFilters;
  onFiltersChange: (filters: PartnerFilters) => void;
}

const partnerTypeOptions = [
  { value: '', label: 'Todos los tipos' },
  { value: 'person', label: 'Persona física' },
  { value: 'company', label: 'Empresa' },
];

const roleOptions = [
  { value: '', label: 'Todos' },
  { value: 'customer', label: 'Clientes' },
  { value: 'supplier', label: 'Proveedores' },
];

const statusOptions = [
  { value: '', label: 'Todos los estados' },
  { value: 'true', label: 'Activos' },
  { value: 'false', label: 'Inactivos' },
];

export function PartnerFiltersPanel({ filters, onFiltersChange }: PartnerFiltersPanelProps) {
  const [searchTerm, setSearchTerm] = useState(filters.search || '');
  const [showFilters, setShowFilters] = useState(false);
  const [selectedRole, setSelectedRole] = useState('');

  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 });
  }

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

  const handleRoleChange = (value: string | string[]) => {
    const role = value as string;
    setSelectedRole(role);

    if (role === 'customer') {
      onFiltersChange({ ...filters, isCustomer: true, isSupplier: undefined, page: 1 });
    } else if (role === 'supplier') {
      onFiltersChange({ ...filters, isSupplier: true, isCustomer: undefined, page: 1 });
    } else {
      onFiltersChange({ ...filters, isCustomer: undefined, isSupplier: undefined, page: 1 });
    }
  };

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

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

  const hasActiveFilters =
    filters.search ||
    filters.partnerType ||
    filters.isCustomer !== undefined ||
    filters.isSupplier !== undefined ||
    filters.active !== undefined;

  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, email 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-48">
            <label className="mb-1 block text-sm font-medium text-gray-700">
              Tipo
            </label>
            <Select
              options={partnerTypeOptions}
              value={filters.partnerType || ''}
              onChange={handleTypeChange}
              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={selectedRole}
              onChange={handleRoleChange}
              placeholder="Seleccionar..."
            />
          </div>

          <div className="w-48">
            <label className="mb-1 block text-sm font-medium text-gray-700">
              Estado
            </label>
            <Select
              options={statusOptions}
              value={filters.active !== undefined ? String(filters.active) : ''}
              onChange={handleStatusChange}
              placeholder="Seleccionar..."
            />
          </div>
        </div>
      )}
    </div>
  );
}
