"use client";

import { useQuery } from "@tanstack/react-query";
import { healthcareApi } from "@/src/modules/healthcare/services/healthcare-api";
import { useTenantId } from "@/hooks/useTenantId";

/** Shared healthcare context data for cross-page lookups (doctors, patients, clinics). */
export function useHealthcareLookups() {
  const { tenantId } = useTenantId();

  const clinicsQ = useQuery({
    queryKey: ["healthcare", tenantId, "lookups", "clinics"],
    queryFn: () => healthcareApi.clinics.list(tenantId!),
    enabled: !!tenantId,
  });

  const doctorsQ = useQuery({
    queryKey: ["healthcare", tenantId, "lookups", "doctors"],
    queryFn: () => healthcareApi.doctors.list(tenantId!),
    enabled: !!tenantId,
  });

  const patientsQ = useQuery({
    queryKey: ["healthcare", tenantId, "lookups", "patients"],
    queryFn: () => healthcareApi.patients.list(tenantId!),
    enabled: !!tenantId,
  });

  const doctorName = (id: string) =>
    doctorsQ.data?.find((d) => d.id === id)?.display_name ?? id.slice(0, 8);

  const patientName = (id: string) =>
    patientsQ.data?.find((p) => p.id === id)?.display_name ?? id.slice(0, 8);

  const clinicName = (id: string) =>
    clinicsQ.data?.find((c) => c.id === id)?.name ?? id.slice(0, 8);

  return {
    tenantId,
    clinics: clinicsQ.data ?? [],
    doctors: doctorsQ.data ?? [],
    patients: patientsQ.data ?? [],
    doctorName,
    patientName,
    clinicName,
    isLoading: clinicsQ.isLoading || doctorsQ.isLoading || patientsQ.isLoading,
    refetchAll: () => {
      clinicsQ.refetch();
      doctorsQ.refetch();
      patientsQ.refetch();
    },
  };
}
