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 dark:bg-[#1c1c1c] border border-slate-200 dark:border-[#2a2a2a] shadow-2xl 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-xl md:w-full overflow-hidden">
          
          {/* Header */}
          <div className="flex items-center justify-between px-6 py-4 border-b border-gray-100 dark:border-[#2a2a2a] bg-white dark:bg-[#1c1c1c]">
            <div className="flex items-center gap-3">
              <Filter className="w-5 h-5 text-gray-500 dark:text-stone-400 fill-gray-500/20" />
              <DialogPrimitive.Title asChild>
                <h2 className="text-lg font-bold text-gray-800 dark:text-white uppercase tracking-tight">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-rose-500 hover:text-rose-600 font-bold text-[10px] uppercase tracking-wider transition-colors"
                >
                    Limpar Tudo
                </button>
                <DialogPrimitive.Close className="rounded-full p-1.5 hover:bg-gray-100 dark:hover:bg-[#2a2a2a] transition-colors">
                    <X className="w-5 h-5 text-gray-400 dark:text-stone-500" />
                    <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-5 bg-white dark:bg-[#1c1c1c] custom-scrollbar">
             {config.map((filter) => {
                const label = filter.label || filter.field.replace(/_/g, ' ').toUpperCase();
                
                if (filter.type === 'select') {
                    return (
                        <div key={filter.field} className="space-y-1.5">
                             <label className="text-[10px] uppercase font-bold text-slate-500 dark:text-stone-500 tracking-widest ml-1">{label}</label>
                             <div className="relative w-full">
                                 <select
                                    className="w-full appearance-none border border-gray-200 dark:border-[#2a2a2a] rounded-xl py-3 pl-4 pr-10 bg-gray-50 dark:bg-[#141414] hover:border-gray-300 dark:hover:border-[#333] transition-all text-left text-sm text-gray-700 dark:text-stone-300 font-bold focus:outline-none focus:border-blue-500 focus:ring-1 focus:ring-blue-500/20"
                                    value={filters[filter.field] || ''}
                                    onChange={(e) => handleChange(filter.field, e.target.value)}
                                 >
                                    <option value="" className="text-gray-400">TODOS</option>
                                    {options[filter.field]?.map(opt => (
                                        <option key={opt} value={opt}>{opt}</option>
                                    ))}
                                 </select>
                                 <div className="absolute right-4 top-1/2 -translate-y-1/2 pointer-events-none">
                                    <ChevronDown className="w-4 h-4 text-gray-400 dark:text-stone-600" />
                                 </div>
                             </div>
                        </div>
                    );
                }

                if (filter.type === 'text') {
                    return (
                        <div key={filter.field} className="space-y-1.5">
                            <label className="text-[10px] uppercase font-bold text-slate-500 dark:text-stone-500 tracking-widest ml-1">{label}</label>
                            <input 
                                type="text" 
                                placeholder={filter.placeholder || "Digite para buscar..."}
                                className="w-full border border-gray-200 dark:border-[#2a2a2a] rounded-xl py-3 px-4 bg-gray-50 dark:bg-[#141414] text-sm text-gray-700 dark:text-white font-bold focus:outline-none focus:border-blue-500 focus:ring-1 focus:ring-blue-500/20 placeholder:text-gray-400 dark:placeholder:text-stone-700 transition-all"
                                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 dark:border-[#2a2a2a] bg-gray-50/50 dark:bg-[#1c1c1c] rounded-b-xl">
            <button 
                onClick={onClose}
                className="px-6 py-2.5 text-xs font-bold uppercase tracking-widest text-gray-500 dark:text-stone-400 hover:text-gray-700 dark:hover:text-white transition-all"
            >
                Cancelar
            </button>
            <button 
                onClick={handleApply}
                className="px-8 py-2.5 text-xs font-bold uppercase tracking-widest text-gray-900 bg-[#fbbf24] hover:bg-[#f59e0b] rounded-xl flex items-center gap-2 transition-all shadow-lg shadow-amber-500/10 active:scale-95"
            >
                <Check className="w-4 h-4" />
                Aplicar Filtros
            </button>
          </div>

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

export default AdvancedFiltersModal;



