import { useQuery } from '@tanstack/react-query'
import { api } from '@/lib/api'
import type { PagedResult } from '@/lib/types'
import { useOrgSettings } from '@/lib/useOrgSettings'

interface EmployeeRow { id: string; userId: string | null }

/** Прогресс по «первым шагам» новой организации: настройки + сотрудники +
 * товары + первая приёмка. Используется в OnboardingPage. */
export function useOnboardingProgress() {
  const org = useOrgSettings()
  const employees = useQuery({
    queryKey: ['onboarding:employees-count'],
    queryFn: async () => (await api.get<PagedResult<EmployeeRow>>('/api/organization/employees?pageSize=1')).data.total,
    staleTime: 60_000,
  })
  const products = useQuery({
    queryKey: ['onboarding:products-count'],
    queryFn: async () => (await api.get<PagedResult<unknown>>('/api/catalog/products?pageSize=1')).data.total,
    staleTime: 60_000,
  })
  const supplies = useQuery({
    queryKey: ['onboarding:supplies-count'],
    queryFn: async () => (await api.get<PagedResult<unknown>>('/api/purchases/supplies?pageSize=1')).data.total,
    staleTime: 60_000,
  })

  const orgConfigured = !!org.data?.defaultCurrencyId && !!org.data?.countryCode
  const hasEmployees = (employees.data ?? 0) > 1 // больше одного admin'а
  const hasProducts = (products.data ?? 0) > 0
  const hasSupplies = (supplies.data ?? 0) > 0

  const steps = { orgConfigured, hasEmployees, hasProducts, hasSupplies }
  const done = Object.values(steps).filter(Boolean).length
  const total = Object.keys(steps).length
  return {
    isLoading: org.isLoading || employees.isLoading || products.isLoading || supplies.isLoading,
    ...steps,
    doneCount: done,
    totalCount: total,
    overall: total === 0 ? 0 : Math.round((done / total) * 100),
    allDone: done === total,
  }
}
