import React from 'react';
import { X, Filter, Trash2, Check, ChevronDown } from 'lucide-react';
import * as DialogPrimitive from '@radix-ui/react-dialog';

const AdvancedFiltersModal = ({ isOpen, onClose, onApply, options = {}, initialFilters = {}, config = [] }) => {
  const [filters, setFilters] = React.useState(initialFilters);

  // Sync with parent when modal opens or initialFilters change
  React.useEffect(() => {
    if (isOpen) {
        setFilters(initialFilters);
    }
  }, [isOpen, initialFilters]);

  const handleChange = (key, value) => {
    setFilters(prev => ({ ...prev, [key]: value }));
  };

  const handleApply = () => {
    onApply(filters);
  };

  const handleClear = () => {
    setFilters({});
  };

  const activeCount = Object.values(filters).filter(Boolean).length;

  return (
    <DialogPrimitive.Root open={isOpen} onOpenChange={onClose}>
      <DialogPrimitive.Portal>
        <DialogPrimitive.Overlay className="fixed inset-0 bg-black/70 z-50 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0" />
        <DialogPrimitive.Content className="fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-0 bg-white shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg md:w-full">
          
          {/* Header */}
          <div className="flex items-center justify-between px-6 py-4 border-b border-gray-100">
            <div className="flex items-center gap-3">
              <Filter className="w-5 h-5 text-gray-500 fill-gray-500" />
              <DialogPrimitive.Title asChild>
                <h2 className="text-lg font-bold text-gray-800">Filtros Avançados</h2>
              </DialogPrimitive.Title>
              <DialogPrimitive.Description className="sr-only">
                Selecione os filtros detalhados para refinar a busca de veículos.
              </DialogPrimitive.Description>
              {activeCount > 0 && (
                <span className="bg-blue-500 text-white text-xs font-bold px-3 py-1 rounded-full">
                    {activeCount} filtros ativos
                </span>
              )}
            </div>
            <div className="flex items-center gap-4">
                <button 
                    onClick={handleClear}
                    className="flex items-center gap-1 text-red-500 hover:text-red-700 font-medium text-sm transition-colors"
                >
                    <span className="text-xs">☰</span> Limpar
                </button>
                <DialogPrimitive.Close className="rounded-full p-1 hover:bg-gray-100 transition-colors">
                    <X className="w-5 h-5 text-gray-400" />
                    <span className="sr-only">Close</span>
                </DialogPrimitive.Close>
            </div>
          </div>

          {/* Body - Scrollable Form */}
          <div className="px-6 py-6 max-h-[60vh] overflow-y-auto space-y-4">
             {config.map((filter) => {
                if (filter.type === 'select') {
                    return (
                        <div key={filter.field} className="relative">
                             <div className="relative w-full">
                                 <select
                                    className="w-full appearance-none border border-gray-200 rounded-md py-3 pl-3 pr-8 bg-white hover:border-gray-300 transition-colors text-left text-sm text-gray-700 font-medium focus:outline-none focus:border-blue-500"
                                    value={filters[filter.field] || ''}
                                    onChange={(e) => handleChange(filter.field, e.target.value)}
                                 >
                                    <option value="" className="text-gray-400">{filter.label}</option>
                                    {options[filter.field]?.map(opt => (
                                        <option key={opt} value={opt}>{opt}</option>
                                    ))}
                                 </select>
                                 <div className="absolute right-3 top-1/2 -translate-y-1/2 pointer-events-none">
                                    <ChevronDown className="w-4 h-4 text-gray-400" />
                                 </div>
                             </div>
                        </div>
                    );
                }

                if (filter.type === 'text') {
                    return (
                        <div key={filter.field} className="relative group">
                            <span className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-700 font-medium text-sm">{filter.label}</span>
                            <input 
                                type="text" 
                                placeholder={filter.placeholder}
                                className="w-full border border-gray-200 rounded-md py-3 pl-[var(--padding-left)] pr-3 text-sm focus:outline-none focus:border-blue-500 placeholder:text-gray-400 transition-colors"
                                style={{ '--padding-left': `${filter.label.length * 8 + 24}px` }} // dynamic padding approx
                                value={filters[filter.field] || ''}
                                onChange={(e) => handleChange(filter.field, e.target.value)}
                            />
                         </div>
                    );
                }
                
                return null;
             })}
          </div>

          {/* Footer */}
          <div className="flex items-center justify-end gap-3 px-6 py-4 border-t border-gray-100 bg-white rounded-b-lg">
            <button 
                onClick={onClose}
                className="px-4 py-2 text-sm font-medium text-gray-600 bg-white border border-gray-200 rounded hover:bg-gray-50 transition-colors"
            >
                Cancelar
            </button>
            <button 
                onClick={handleApply}
                className="px-4 py-2 text-sm font-bold text-gray-900 bg-[#fbbf24] hover:bg-[#f59e0b] rounded flex items-center gap-2 transition-colors shadow-sm"
            >
                <Check className="w-4 h-4" />
                Aplicar Filtros
            </button>
          </div>

        </DialogPrimitive.Content>
      </DialogPrimitive.Portal>
    </DialogPrimitive.Root>
  );
};

export default AdvancedFiltersModal;
