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

/**
 * Modal de Filtros Avançados — adaptado ao dark mode e paleta indigo do ambiente RH.
 */
const AdvancedFiltersModal = ({ isOpen, onClose, onApply, options = {}, initialFilters = {}, config = [] }) => {
  const [filters, setFilters] = React.useState(initialFilters);

  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>

        {/* Overlay */}
        <DialogPrimitive.Overlay className="fixed inset-0 bg-black/60 dark:bg-black/75 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" />

        {/* Panel */}
        <DialogPrimitive.Content className="
          fixed left-1/2 top-1/2 z-50 w-full max-w-md -translate-x-1/2 -translate-y-1/2
          bg-white dark:bg-[#161616]
          border border-slate-200 dark:border-white/[0.07]
          rounded-2xl shadow-2xl shadow-black/20 dark:shadow-black/50
          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%]
        ">

          {/* ── Header ── */}
          <div className="flex items-center justify-between px-5 py-4 border-b border-slate-100 dark:border-white/[0.07]">
            <div className="flex items-center gap-2.5">
              <div className="w-8 h-8 rounded-xl bg-indigo-500/10 dark:bg-indigo-500/15 flex items-center justify-center">
                <Filter className="w-4 h-4 text-indigo-500" />
              </div>
              <DialogPrimitive.Title asChild>
                <h2 className="text-sm font-bold text-slate-800 dark:text-white 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-indigo-500 text-white text-[10px] font-bold px-2.5 py-0.5 rounded-full">
                  {activeCount} ativo{activeCount > 1 ? 's' : ''}
                </span>
              )}
            </div>

            <div className="flex items-center gap-3">
              <button
                onClick={handleClear}
                className="text-[11px] font-semibold text-slate-400 dark:text-slate-500 hover:text-rose-500 dark:hover:text-rose-400 transition-colors uppercase tracking-wider"
              >
                Limpar
              </button>
              <DialogPrimitive.Close className="w-7 h-7 rounded-lg flex items-center justify-center hover:bg-slate-100 dark:hover:bg-white/10 transition-colors">
                <X className="w-4 h-4 text-slate-400 dark:text-slate-500" />
                <span className="sr-only">Fechar</span>
              </DialogPrimitive.Close>
            </div>
          </div>

          {/* ── Body ── */}
          <div className="px-5 py-5 max-h-[60vh] overflow-y-auto space-y-4">
            {config.length === 0 && (
              <p className="text-xs text-slate-400 dark:text-slate-500 text-center py-4 italic">
                Nenhum filtro disponível.
              </p>
            )}

            {config.map((filter) => {
              if (filter.type === 'select') {
                return (
                  <div key={filter.field} className="flex flex-col gap-1.5">
                    <label className="text-[10px] font-bold text-slate-400 dark:text-slate-500 uppercase tracking-widest pl-1">
                      {filter.label}
                    </label>
                    <div className="relative">
                      <select
                        className="
                          w-full appearance-none
                          bg-slate-50 dark:bg-[#1f1f1f]
                          border border-slate-200 dark:border-white/[0.08]
                          hover:border-indigo-400 dark:hover:border-indigo-500/60
                          focus:border-indigo-500 dark:focus:border-indigo-500
                          focus:ring-2 focus:ring-indigo-500/15
                          text-slate-700 dark:text-slate-200
                          rounded-xl py-2.5 pl-4 pr-9
                          text-xs font-medium
                          transition-all outline-none
                        "
                        value={filters[filter.field] || ''}
                        onChange={(e) => handleChange(filter.field, e.target.value)}
                      >
                        <option value="">Todos</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-3.5 h-3.5 text-slate-400 dark:text-slate-500" />
                      </div>
                    </div>
                  </div>
                );
              }

              if (filter.type === 'text') {
                return (
                  <div key={filter.field} className="flex flex-col gap-1.5">
                    <label className="text-[10px] font-bold text-slate-400 dark:text-slate-500 uppercase tracking-widest pl-1">
                      {filter.label}
                    </label>
                    <input
                      type="text"
                      placeholder={filter.placeholder || `Buscar por ${filter.label}...`}
                      className="
                        w-full
                        bg-slate-50 dark:bg-[#1f1f1f]
                        border border-slate-200 dark:border-white/[0.08]
                        hover:border-indigo-400 dark:hover:border-indigo-500/60
                        focus:border-indigo-500 dark:focus:border-indigo-500
                        focus:ring-2 focus:ring-indigo-500/15
                        text-slate-700 dark:text-slate-200
                        placeholder:text-slate-400 dark:placeholder:text-slate-600
                        rounded-xl py-2.5 px-4 text-xs
                        transition-all outline-none
                      "
                      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-2.5 px-5 py-4 border-t border-slate-100 dark:border-white/[0.07] rounded-b-2xl bg-slate-50/50 dark:bg-[#111111]/50">
            <button
              onClick={onClose}
              className="
                px-4 py-2 text-xs font-semibold
                text-slate-600 dark:text-slate-400
                bg-white dark:bg-white/5
                border border-slate-200 dark:border-white/[0.08]
                hover:border-slate-300 dark:hover:border-white/20
                rounded-xl transition-all
              "
            >
              Cancelar
            </button>
            <button
              onClick={handleApply}
              className="
                px-5 py-2 text-xs font-bold
                text-white bg-indigo-600 hover:bg-indigo-700
                dark:bg-indigo-500 dark:hover:bg-indigo-600
                rounded-xl flex items-center gap-1.5
                transition-all shadow-lg shadow-indigo-500/20
                active:scale-95
              "
            >
              <Check className="w-3.5 h-3.5" />
              Aplicar Filtros
            </button>
          </div>

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

export default AdvancedFiltersModal;
