"use client";

import { useQuery } from "@tanstack/react-query";
import { beautyBusinessApi } from "@/modules/beauty/services/beauty-business-api";
import { useTenantId } from "@/hooks/useTenantId";

/** Shared beauty context data for cross-page lookups. */
export function useBeautyLookups() {
  const { tenantId } = useTenantId();

  const orgsQ = useQuery({
    queryKey: ["beauty", tenantId, "lookups", "organizations"],
    queryFn: () => beautyBusinessApi.organizations.list(tenantId!),
    enabled: !!tenantId,
  });

  const branchesQ = useQuery({
    queryKey: ["beauty", tenantId, "lookups", "branches"],
    queryFn: () => beautyBusinessApi.branches.list(tenantId!),
    enabled: !!tenantId,
  });

  const staffQ = useQuery({
    queryKey: ["beauty", tenantId, "lookups", "staff"],
    queryFn: () => beautyBusinessApi.staff.list(tenantId!),
    enabled: !!tenantId,
  });

  const customersQ = useQuery({
    queryKey: ["beauty", tenantId, "lookups", "customers"],
    queryFn: () => beautyBusinessApi.customers.list(tenantId!),
    enabled: !!tenantId,
  });

  const servicesQ = useQuery({
    queryKey: ["beauty", tenantId, "lookups", "services"],
    queryFn: () => beautyBusinessApi.services.list(tenantId!),
    enabled: !!tenantId,
  });

  const orgName = (id: string) =>
    orgsQ.data?.find((o) => o.id === id)?.name ?? id.slice(0, 8);

  const branchName = (id: string) =>
    branchesQ.data?.find((b) => b.id === id)?.name ?? id.slice(0, 8);

  const staffName = (id: string | null | undefined) =>
    id ? staffQ.data?.find((s) => s.id === id)?.display_name ?? id.slice(0, 8) : "—";

  const customerName = (id: string | null | undefined) =>
    id ? customersQ.data?.find((c) => c.id === id)?.display_name ?? id.slice(0, 8) : "—";

  const serviceName = (id: string | null | undefined) =>
    id ? servicesQ.data?.find((s) => s.id === id)?.name ?? id.slice(0, 8) : "—";

  return {
    tenantId,
    organizations: orgsQ.data ?? [],
    branches: branchesQ.data ?? [],
    staff: staffQ.data ?? [],
    customers: customersQ.data ?? [],
    services: servicesQ.data ?? [],
    orgName,
    branchName,
    staffName,
    customerName,
    serviceName,
    isLoading:
      orgsQ.isLoading ||
      branchesQ.isLoading ||
      staffQ.isLoading ||
      customersQ.isLoading ||
      servicesQ.isLoading,
    refetchAll: () => {
      orgsQ.refetch();
      branchesQ.refetch();
      staffQ.refetch();
      customersQ.refetch();
      servicesQ.refetch();
    },
  };
}
