'use client';

import { useEffect, useState } from 'react';
import { patientsApi } from '@/lib/api/patients';
import { useAuth } from '@/lib/hooks/useAuth';
import type { Patient } from '@/types/patient';

/** Debounced patient search — only queries when `search` is non-empty. */
export function usePatientSearchQuery(enabled = true) {
  const { currentOrganization } = useAuth();
  const [search, setSearch] = useState('');
  const [patients, setPatients] = useState<Patient[]>([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (!enabled || !currentOrganization) {
      return;
    }

    const trimmed = search.trim();
    if (!trimmed) {
      setPatients([]);
      setLoading(false);
      return;
    }

    const timeout = setTimeout(() => {
      void (async () => {
        setLoading(true);
        try {
          const response = await patientsApi.list({ q: trimmed, page: 1, limit: 25 });
          setPatients(response.data.items ?? []);
        } catch {
          setPatients([]);
        } finally {
          setLoading(false);
        }
      })();
    }, 300);

    return () => clearTimeout(timeout);
  }, [search, enabled, currentOrganization]);

  return { search, setSearch, patients, loading };
}
