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

function 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/80 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-slate-900 border border-slate-200 dark:border-slate-800 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-slate-200 dark:border-slate-800 bg-white dark:bg-slate-900">
            <div className="flex items-center gap-3">
              <Filter className="w-5 h-5 text-blue-600 dark:text-blue-500" />
              <DialogPrimitive.Title asChild>
                <h2 className="text-lg font-bold text-slate-900 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.
              </DialogPrimitive.Description>
              {activeCount > 0 && (
                <span className="bg-blue-600 dark:bg-blue-500 text-white text-xs font-bold px-3 py-1 rounded-full">
                    {activeCount} filtros ativos
                </span>
              )}
            </div>
            <DialogPrimitive.Close asChild>
              <button className="p-2 hover:bg-slate-100 dark:hover:bg-slate-800 rounded-lg transition-colors">
                <X size={18} className="text-slate-600 dark:text-slate-400" />
              </button>
            </DialogPrimitive.Close>
          </div>

          {/* Content */}
          <div className="p-6 space-y-4 max-h-[60vh] overflow-y-auto">
            {config.length === 0 ? (
              <p className="text-sm text-slate-500 dark:text-slate-400 text-center py-8">
                Nenhum filtro configurado.
              </p>
            ) : (
              config.map((def) => (
                <div key={def.field} className="space-y-2">
                  <label className="text-xs font-bold uppercase tracking-wider text-slate-700 dark:text-slate-300">
                    {def.label || def.field}
                  </label>
                  {def.type === 'select' && options[def.field] ? (
                    <select
                      value={filters[def.field] || ''}
                      onChange={(e) => handleChange(def.field, e.target.value)}
                      className="w-full px-3 py-2 border border-slate-300 dark:border-slate-700 rounded-lg bg-white dark:bg-slate-800 text-slate-900 dark:text-white text-sm"
                    >
                      <option value="">Todos</option>
                      {options[def.field].map((opt) => (
                        <option key={opt} value={opt}>
                          {opt}
                        </option>
                      ))}
                    </select>
                  ) : (
                    <input
                      type="text"
                      value={filters[def.field] || ''}
                      onChange={(e) => handleChange(def.field, e.target.value)}
                      placeholder={`Filtrar por ${def.label || def.field}`}
                      className="w-full px-3 py-2 border border-slate-300 dark:border-slate-700 rounded-lg bg-white dark:bg-slate-800 text-slate-900 dark:text-white text-sm"
                    />
                  )}
                </div>
              ))
            )}
          </div>

          {/* Footer */}
          <div className="flex items-center justify-between px-6 py-4 border-t border-slate-200 dark:border-slate-800 bg-slate-50 dark:bg-slate-900/50">
            <button
              onClick={handleClear}
              className="flex items-center gap-2 px-4 py-2 text-sm font-semibold text-slate-600 dark:text-slate-400 hover:text-slate-900 dark:hover:text-slate-200 transition-colors"
            >
              <Trash2 size={16} />
              Limpar
            </button>
            <div className="flex gap-2">
              <DialogPrimitive.Close asChild>
                <button className="px-4 py-2 text-sm font-semibold text-slate-600 dark:text-slate-400 hover:text-slate-900 dark:hover:text-slate-200 transition-colors">
                  Cancelar
                </button>
              </DialogPrimitive.Close>
              <button
                onClick={handleApply}
                className="flex items-center gap-2 px-4 py-2 bg-blue-600 dark:bg-blue-500 hover:bg-blue-700 dark:hover:bg-blue-600 text-white text-sm font-semibold rounded-lg transition-colors"
              >
                <Check size={16} />
                Aplicar Filtros
              </button>
            </div>
          </div>
        </DialogPrimitive.Content>
      </DialogPrimitive.Portal>
    </DialogPrimitive.Root>
  );
};

export default AdvancedFiltersModal;
