import { useState, useEffect, useRef, useMemo } from 'react';
import { Search, X, FileText, Pill, Stethoscope, AlertTriangle } from 'lucide-react';
import { useNavigate } from 'react-router-dom';
import { useSearch, SearchItem } from '@/hooks/useSearch';

interface SearchModalProps {
  isOpen: boolean;
  onClose: () => void;
}

const typeIcons = {
  protocol: FileText,
  procedure: Stethoscope,
  drug: Pill,
};

const SearchModal = ({ isOpen, onClose }: SearchModalProps) => {
  const [query, setQuery] = useState('');
  const inputRef = useRef<HTMLInputElement>(null);
  const navigate = useNavigate();
  const { search, categories } = useSearch();

  const results = useMemo(() => {
    return query.length >= 2 ? search(query) : [];
  }, [query, search]);

  useEffect(() => {
    if (isOpen && inputRef.current) {
      inputRef.current.focus();
    }
  }, [isOpen]);

  useEffect(() => {
    if (!isOpen) {
      setQuery('');
    }
  }, [isOpen]);

  const handleResultClick = (result: SearchItem) => {
    navigate(result.path);
    onClose();
    setQuery('');
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-[100] bg-background/95 backdrop-blur-sm">
      <div className="flex flex-col h-full max-w-2xl mx-auto p-4">
        <div className="flex items-center gap-3 mb-4">
          <div className="flex-1 relative">
            <Search className="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-muted-foreground" />
            <input
              ref={inputRef}
              type="text"
              value={query}
              onChange={(e) => setQuery(e.target.value)}
              placeholder="Buscar protocolo, fármaco, calculadora..."
              className="w-full h-14 pl-12 pr-4 bg-card border border-border rounded-xl text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary"
            />
          </div>
          <button
            onClick={onClose}
            className="w-14 h-14 flex items-center justify-center rounded-xl bg-card border border-border hover:bg-muted transition-colors"
            aria-label="Cerrar búsqueda"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        <div className="flex-1 overflow-y-auto scroll-touch">
          {query.length >= 2 ? (
            results.length > 0 ? (
              <div className="space-y-6">
                {Object.entries(
                  results.reduce((acc, result) => {
                    const cat = result.category;
                    if (!acc[cat]) acc[cat] = [];
                    acc[cat].push(result);
                    return acc;
                  }, {} as Record<string, SearchItem[]>)
                ).map(([category, items]) => (
                  <div key={category}>
                    <h3 className="text-sm font-medium text-muted-foreground mb-2 px-1">
                      {categories[category] || category}
                    </h3>
                    <div className="space-y-2">
                      {items.map((result) => {
                        const Icon = typeIcons[result.type] || FileText;
                        return (
                          <button
                            key={result.id}
                            onClick={() => handleResultClick(result)}
                            className="w-full flex items-center gap-4 p-4 bg-card border border-border rounded-xl hover:border-primary/50 active:bg-muted/50 active:scale-[0.99] transition-all text-left"
                          >
                            <div className="w-10 h-10 rounded-lg bg-muted flex items-center justify-center flex-shrink-0">
                              <Icon className="w-5 h-5 text-primary" />
                            </div>
                            <div className="flex-1 min-w-0">
                              <p className="font-medium text-foreground truncate">{result.title}</p>
                              <p className="text-xs text-muted-foreground capitalize">{result.type}</p>
                            </div>
                            <Search className="w-5 h-5 text-muted-foreground flex-shrink-0" />
                          </button>
                        );
                      })}
                    </div>
                  </div>
                ))}
              </div>
            ) : (
              <div className="flex flex-col items-center justify-center py-12 text-center">
                <AlertTriangle className="w-12 h-12 text-muted-foreground mb-4" />
                <p className="text-foreground">Sin resultados</p>
                <p className="text-sm text-muted-foreground mt-1">
                  Prueba con otras palabras
                </p>
              </div>
            )
          ) : (
            <div className="flex flex-col items-center justify-center py-12 text-center">
              <Search className="w-12 h-12 text-muted-foreground mb-4" />
              <p className="text-foreground">Escribe para buscar</p>
              <p className="text-sm text-muted-foreground mt-1">Protocolos, fármacos, calculadoras...</p>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default SearchModal;
