import React from 'react';
import { Search, Filter } from 'lucide-react';
import { Input } from '../Input';
import { Button } from '../Button';
import { Card } from '../Card';
import { Select } from '../Select';
import { Toggle } from '../Toggle';

export interface FilterOption {
  value: string;
  label: string;
  count?: number;
}

export interface FilterConfig {
  key: string;
  label: string;
  type: 'dropdown' | 'buttons' | 'checkbox';
  options?: FilterOption[];
  value: string | string[] | boolean;
  onChange: (value: string | string[] | boolean) => void;
  placeholder?: string;
  multiple?: boolean;
}

export interface SearchAndFilterProps {
  // Search configuration
  searchValue: string;
  onSearchChange: (value: string) => void;
  searchPlaceholder?: string;

  // Filter configuration
  filters?: FilterConfig[];

  // Layout configuration
  className?: string;
  showFilterIcon?: boolean;

  // Mobile responsive behavior
  stackOnMobile?: boolean;
}

export const SearchAndFilter: React.FC<SearchAndFilterProps> = ({
  searchValue,
  onSearchChange,
  searchPlaceholder = "Buscar...",
  filters = [],
  className = "",
  showFilterIcon = true,
  stackOnMobile = true
}) => {
  const renderDropdownFilter = (filter: FilterConfig) => {
    const currentValue = filter.value as string;

    // Convert FilterOptions to SelectOptions format
    const selectOptions = [
      { value: '', label: filter.placeholder || `Todos ${filter.label.toLowerCase()}` },
      ...(filter.options?.map(option => ({
        value: option.value,
        label: option.count !== undefined ? `${option.label} (${option.count})` : option.label
      })) || [])
    ];

    return (
      <div key={filter.key} className="min-w-[140px]">
        <Select
          value={currentValue}
          onChange={(value) => filter.onChange(value)}
          options={selectOptions}
          placeholder={filter.placeholder}
        />
      </div>
    );
  };

  const renderButtonFilter = (filter: FilterConfig) => {
    const currentValues = Array.isArray(filter.value) ? filter.value : [filter.value];

    return (
      <div key={filter.key} className="flex items-center gap-2 flex-wrap">
        {filter.options?.map((option) => {
          const isActive = currentValues.includes(option.value);
          return (
            <Button
              key={option.value}
              variant={isActive ? "primary" : "outline"}
              size="sm"
              onClick={() => {
                if (filter.multiple) {
                  const newValues = isActive
                    ? currentValues.filter(v => v !== option.value)
                    : [...currentValues, option.value];
                  filter.onChange(newValues);
                } else {
                  filter.onChange(isActive ? "" : option.value);
                }
              }}
              className={`text-sm px-3 py-1.5 ${
                isActive
                  ? 'bg-[var(--primary)] text-white'
                  : 'text-[var(--text-secondary)] hover:text-[var(--text-primary)]'
              }`}
            >
              {option.label}
              {option.count !== undefined && (
                <span className={`ml-1 ${isActive ? 'text-white/80' : 'text-[var(--text-tertiary)]'}`}>
                  ({option.count})
                </span>
              )}
            </Button>
          );
        })}
      </div>
    );
  };

  const renderCheckboxFilter = (filter: FilterConfig) => {
    const isChecked = filter.value as boolean;

    return (
      <div key={filter.key} className="flex items-center">
        <Toggle
          checked={isChecked}
          onChange={(checked) => filter.onChange(checked)}
          label={filter.label}
          size="sm"
        />
      </div>
    );
  };

  const renderFilter = (filter: FilterConfig) => {
    switch (filter.type) {
      case 'dropdown':
        return renderDropdownFilter(filter);
      case 'buttons':
        return renderButtonFilter(filter);
      case 'checkbox':
        return renderCheckboxFilter(filter);
      default:
        return null;
    }
  };

  return (
    <Card className={`p-4 ${className}`}>
      <div className={`flex gap-4 ${stackOnMobile ? 'flex-col sm:flex-row' : 'flex-row'}`}>
        {/* Search Input */}
        <div className="flex-1 min-w-0">
          <div className="relative">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-[var(--text-tertiary)]" />
            <Input
              type="text"
              placeholder={searchPlaceholder}
              value={searchValue}
              onChange={(e) => onSearchChange(e.target.value)}
              className="pl-10 w-full"
            />
          </div>
        </div>

        {/* Filters */}
        {filters.length > 0 && (
          <div className={`flex items-center gap-3 ${stackOnMobile ? 'flex-wrap' : ''}`}>
            {showFilterIcon && (
              <Filter className="w-4 h-4 text-[var(--text-tertiary)] flex-shrink-0" />
            )}
            {filters.map(renderFilter)}
          </div>
        )}
      </div>
    </Card>
  );
};

export default SearchAndFilter;