import type { FC } from 'react';
import { useEffect, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Search, Users, Calendar, Briefcase } from 'lucide-react';
import { odooApi } from '../services/odoo';

interface Results {
  patients: { id: number; name: string; phone: string }[];
  appointments: { id: number; patient: string; service: string; date: string; time: string }[];
  services: { id: number; name: string; price: number }[];
}

const EMPTY: Results = { patients: [], appointments: [], services: [] };

interface GlobalSearchProps {
  placeholder?: string;
  className?: string;
}

/** Búsqueda global del header: dropdown con autocompletado (pacientes, citas, servicios). */
export const GlobalSearch: FC<GlobalSearchProps> = ({ placeholder = 'Buscar paciente, cita, servicio...', className = '' }) => {
  const navigate = useNavigate();
  const [query, setQuery] = useState('');
  const [results, setResults] = useState<Results>(EMPTY);
  const [open, setOpen] = useState(false);
  const [searching, setSearching] = useState(false);
  const boxRef = useRef<HTMLDivElement>(null);

  // Cerrar al hacer click fuera
  useEffect(() => {
    const close = (e: MouseEvent) => {
      if (boxRef.current && !boxRef.current.contains(e.target as Node)) setOpen(false);
    };
    document.addEventListener('mousedown', close);
    return () => document.removeEventListener('mousedown', close);
  }, []);

  // Búsqueda con debounce
  useEffect(() => {
    const q = query.trim();
    if (q.length < 2) {
      setResults(EMPTY);
      setSearching(false);
      return;
    }
    setSearching(true);
    const t = setTimeout(async () => {
      try {
        const res = await odooApi.globalSearch(q);
        if (res.status === 'success') {
          setResults({
            patients: res.patients || [],
            appointments: res.appointments || [],
            services: res.services || [],
          });
          setOpen(true);
        }
      } catch {
        setResults(EMPTY);
      } finally {
        setSearching(false);
      }
    }, 250);
    return () => clearTimeout(t);
  }, [query]);

  const go = (path: string) => {
    setOpen(false);
    setQuery('');
    navigate(path);
  };

  const hasResults = results.patients.length + results.appointments.length + results.services.length > 0;
  const showDropdown = open && query.trim().length >= 2;

  return (
    <div ref={boxRef} className={`relative ${className}`}>
      <div className="flex items-center rounded-full px-3 py-1.5 border" style={{ backgroundColor: 'var(--bg)', borderColor: 'var(--border)' }}>
        <Search size={14} style={{ color: 'var(--text-muted)' }} />
        <input
          type="text"
          value={query}
          placeholder={placeholder}
          onChange={(e) => setQuery(e.target.value)}
          onFocus={() => { if (hasResults) setOpen(true); }}
          onKeyDown={(e) => { if (e.key === 'Escape') setOpen(false); }}
          className="bg-transparent border-none text-sm ml-2 focus:outline-none w-48 placeholder:text-theme-muted/60"
          style={{ color: 'var(--text-heading)' }}
        />
      </div>

      {showDropdown && (
        <div className="absolute right-0 top-full mt-2 w-80 max-h-[70vh] overflow-y-auto rounded-2xl border border-theme-border bg-theme-surface shadow-card z-50">
          {searching && (
            <p className="px-4 py-3 text-xs text-theme-muted">Buscando...</p>
          )}
          {!searching && !hasResults && (
            <p className="px-4 py-3 text-xs text-theme-muted">Sin resultados para "{query.trim()}"</p>
          )}

          {results.patients.length > 0 && (
            <div className="p-1.5">
              <p className="px-2.5 py-1 text-[10px] uppercase tracking-wider text-theme-muted font-medium">Pacientes</p>
              {results.patients.map((p) => (
                <button
                  key={`p-${p.id}`}
                  type="button"
                  onClick={() => go(`/pacientes?q=${encodeURIComponent(p.phone || p.name)}`)}
                  className="w-full flex items-center gap-2.5 px-2.5 py-2 rounded-xl text-sm text-theme-heading hover:bg-theme-accent-bg transition-colors text-left"
                >
                  <Users size={15} className="text-theme-muted shrink-0" />
                  <span className="truncate">{p.name}</span>
                  <span className="ml-auto text-xs text-theme-muted shrink-0">{p.phone}</span>
                </button>
              ))}
            </div>
          )}

          {results.appointments.length > 0 && (
            <div className="p-1.5 border-t border-theme-border">
              <p className="px-2.5 py-1 text-[10px] uppercase tracking-wider text-theme-muted font-medium">Citas próximas</p>
              {results.appointments.map((a) => (
                <button
                  key={`a-${a.id}`}
                  type="button"
                  onClick={() => go(`/agenda?date=${a.date}`)}
                  className="w-full flex items-center gap-2.5 px-2.5 py-2 rounded-xl text-sm text-theme-heading hover:bg-theme-accent-bg transition-colors text-left"
                >
                  <Calendar size={15} className="text-theme-muted shrink-0" />
                  <span className="truncate">{a.patient} · {a.service}</span>
                  <span className="ml-auto text-xs text-theme-muted shrink-0">{a.date.slice(5)} {a.time}</span>
                </button>
              ))}
            </div>
          )}

          {results.services.length > 0 && (
            <div className="p-1.5 border-t border-theme-border">
              <p className="px-2.5 py-1 text-[10px] uppercase tracking-wider text-theme-muted font-medium">Servicios</p>
              {results.services.map((s) => (
                <button
                  key={`s-${s.id}`}
                  type="button"
                  onClick={() => go(`/servicios?q=${encodeURIComponent(s.name)}`)}
                  className="w-full flex items-center gap-2.5 px-2.5 py-2 rounded-xl text-sm text-theme-heading hover:bg-theme-accent-bg transition-colors text-left"
                >
                  <Briefcase size={15} className="text-theme-muted shrink-0" />
                  <span className="truncate">{s.name}</span>
                  <span className="ml-auto text-xs text-theme-muted shrink-0">${s.price}</span>
                </button>
              ))}
            </div>
          )}
        </div>
      )}
    </div>
  );
};

export default GlobalSearch;
