'use client'

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import {
  getSettings,
  updateSettings,
  getSetting,
  updateSetting,
  deleteSetting,
} from '@/lib/api/admin'
import type { UpdateSettingsPayload } from '@/types/api'

// Query keys
export const settingsKeys = {
  all: ['settings'] as const,
  list: () => [...settingsKeys.all, 'list'] as const,
  category: (category: string) => [...settingsKeys.all, 'category', category] as const,
  detail: (key: string) => [...settingsKeys.all, 'detail', key] as const,
}

// Hooks

/**
 * Fetch all settings (grouped by category)
 */
export function useSettings() {
  return useQuery({
    queryKey: settingsKeys.list(),
    queryFn: () => getSettings(),
  })
}

/**
 * Fetch settings for a specific category
 */
export function useSettingsCategory(category: string) {
  return useQuery({
    queryKey: settingsKeys.category(category),
    queryFn: () => getSettings(category),
    enabled: !!category,
  })
}

/**
 * Fetch a single setting
 */
export function useSetting(key: string) {
  return useQuery({
    queryKey: settingsKeys.detail(key),
    queryFn: () => getSetting(key),
    enabled: !!key,
  })
}

/**
 * Batch update settings
 */
export function useUpdateSettings() {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: (data: UpdateSettingsPayload) => updateSettings(data),
    onSuccess: () => {
      // Invalidate all settings queries
      queryClient.invalidateQueries({ queryKey: settingsKeys.all })
    },
  })
}

/**
 * Update a single setting
 */
export function useUpdateSetting() {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: ({ key, value }: { key: string; value: string }) =>
      updateSetting(key, { value }),
    onSuccess: (_, variables) => {
      queryClient.invalidateQueries({ queryKey: settingsKeys.detail(variables.key) })
      queryClient.invalidateQueries({ queryKey: settingsKeys.list() })
    },
  })
}

/**
 * Delete a setting (revert to default)
 */
export function useDeleteSetting() {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: (key: string) => deleteSetting(key),
    onSuccess: (_, key) => {
      queryClient.invalidateQueries({ queryKey: settingsKeys.detail(key) })
      queryClient.invalidateQueries({ queryKey: settingsKeys.list() })
    },
  })
}
