/**
 * Hook for managing enabled/disabled features across the app.
 *
 * Features can be enabled/disabled in the Private Gallery settings.
 * This hook provides the current list of enabled features, their order,
 * custom labels, and helpers to check if a feature is enabled and sort items by order.
 */

import { useQuery } from '@tanstack/react-query'
import { useCallback } from 'react'
import { api } from '../lib/api'

export interface UseEnabledFeaturesResult {
  enabledFeatures: string[]
  featureOrder: Record<string, string[]>
  featureLabels: Record<string, string>
  groupOrder: string[]
  isLoading: boolean
  isFeatureEnabled: (path: string) => boolean
  getFeatureLabel: (path: string, defaultLabel: string) => string
  sortByOrder: <T extends { path: string }>(items: T[], groupId: string) => T[]
  sortGroups: <T extends { id: string }>(groups: T[]) => T[]
  refetch: () => void
}

export function useEnabledFeatures(): UseEnabledFeaturesResult {
  const { data, isLoading, refetch } = useQuery({
    queryKey: ['enabled-features'],
    queryFn: () => api.privateGallery.getEnabledFeatures(),
    staleTime: 5 * 60 * 1000, // 5 minutes - features don't change often
    refetchOnWindowFocus: false,
  })

  const enabledFeatures = data?.enabled_features || []
  const featureOrder = data?.feature_order || {}
  const featureLabels = data?.feature_labels || {}
  const groupOrder = data?.group_order || []

  const isFeatureEnabled = useCallback((path: string): boolean => {
    // If still loading, assume enabled to prevent flash of missing content
    if (isLoading) return true
    // Empty list means all features are enabled (default state)
    if (enabledFeatures.length === 0) return true
    return enabledFeatures.includes(path)
  }, [isLoading, enabledFeatures])

  const getFeatureLabel = useCallback((path: string, defaultLabel: string): string => {
    return featureLabels[path] || defaultLabel
  }, [featureLabels])

  const sortByOrder = useCallback(<T extends { path: string }>(items: T[], groupId: string): T[] => {
    const order = featureOrder[groupId]
    if (!order || order.length === 0) return items

    // Sort items based on their position in the order array
    return [...items].sort((a, b) => {
      const aIndex = order.indexOf(a.path)
      const bIndex = order.indexOf(b.path)
      // Items not in order array go to the end
      const aPos = aIndex === -1 ? 9999 : aIndex
      const bPos = bIndex === -1 ? 9999 : bIndex
      return aPos - bPos
    })
  }, [featureOrder])

  const sortGroups = useCallback(<T extends { id: string }>(groups: T[]): T[] => {
    if (!groupOrder || groupOrder.length === 0) return groups

    return [...groups].sort((a, b) => {
      const aIndex = groupOrder.indexOf(a.id)
      const bIndex = groupOrder.indexOf(b.id)
      const aPos = aIndex === -1 ? 9999 : aIndex
      const bPos = bIndex === -1 ? 9999 : bIndex
      return aPos - bPos
    })
  }, [groupOrder])

  return {
    enabledFeatures,
    featureOrder,
    featureLabels,
    groupOrder,
    isLoading,
    isFeatureEnabled,
    getFeatureLabel,
    sortByOrder,
    sortGroups,
    refetch,
  }
}

export default useEnabledFeatures
