// frontend/src/api/hooks/settings.ts
/**
 * React Query hooks for Tenant Settings
 * Provides data fetching, caching, and mutation hooks
 */

import { useQuery, useMutation, useQueryClient, UseQueryOptions } from '@tanstack/react-query';
import { settingsApi } from '../services/settings';
import { showToast } from '../../utils/toast';
import type {
  TenantSettings,
  TenantSettingsUpdate,
  SettingsCategory,
  CategoryResetResponse,
} from '../types/settings';

// Query keys
export const settingsKeys = {
  all: ['settings'] as const,
  tenant: (tenantId: string) => ['settings', tenantId] as const,
  category: (tenantId: string, category: SettingsCategory) =>
    ['settings', tenantId, category] as const,
};

/**
 * Hook to fetch all settings for a tenant
 */
export const useSettings = (
  tenantId: string,
  options?: Omit<UseQueryOptions<TenantSettings, Error>, 'queryKey' | 'queryFn'>
) => {
  return useQuery<TenantSettings, Error>({
    queryKey: settingsKeys.tenant(tenantId),
    queryFn: () => settingsApi.getSettings(tenantId),
    staleTime: 5 * 60 * 1000, // 5 minutes
    ...options,
  });
};

/**
 * Hook to fetch settings for a specific category
 */
export const useCategorySettings = (
  tenantId: string,
  category: SettingsCategory,
  options?: Omit<UseQueryOptions<Record<string, any>, Error>, 'queryKey' | 'queryFn'>
) => {
  return useQuery<Record<string, any>, Error>({
    queryKey: settingsKeys.category(tenantId, category),
    queryFn: () => settingsApi.getCategorySettings(tenantId, category),
    staleTime: 5 * 60 * 1000, // 5 minutes
    ...options,
  });
};

/**
 * Hook to update tenant settings
 */
export const useUpdateSettings = () => {
  const queryClient = useQueryClient();

  return useMutation<
    TenantSettings,
    Error,
    { tenantId: string; updates: TenantSettingsUpdate }
  >({
    mutationFn: ({ tenantId, updates }) => settingsApi.updateSettings(tenantId, updates),
    onSuccess: (data, variables) => {
      // Invalidate all settings queries for this tenant
      queryClient.invalidateQueries({ queryKey: settingsKeys.tenant(variables.tenantId) });
      showToast.success('Ajustes guardados correctamente');
    },
    onError: (error) => {
      console.error('Failed to update settings:', error);
      showToast.error('Error al guardar los ajustes');
    },
  });
};

/**
 * Hook to update a specific category
 */
export const useUpdateCategorySettings = () => {
  const queryClient = useQueryClient();

  return useMutation<
    TenantSettings,
    Error,
    { tenantId: string; category: SettingsCategory; settings: Record<string, any> }
  >({
    mutationFn: ({ tenantId, category, settings }) =>
      settingsApi.updateCategorySettings(tenantId, category, settings),
    onSuccess: (data, variables) => {
      // Invalidate all settings queries for this tenant
      queryClient.invalidateQueries({ queryKey: settingsKeys.tenant(variables.tenantId) });
      // Also invalidate the specific category query
      queryClient.invalidateQueries({
        queryKey: settingsKeys.category(variables.tenantId, variables.category),
      });
      showToast.success('Ajustes de categoría guardados correctamente');
    },
    onError: (error) => {
      console.error('Failed to update category settings:', error);
      showToast.error('Error al guardar los ajustes de categoría');
    },
  });
};

/**
 * Hook to reset a category to defaults
 */
export const useResetCategory = () => {
  const queryClient = useQueryClient();

  return useMutation<
    CategoryResetResponse,
    Error,
    { tenantId: string; category: SettingsCategory }
  >({
    mutationFn: ({ tenantId, category }) => settingsApi.resetCategory(tenantId, category),
    onSuccess: (data, variables) => {
      // Invalidate all settings queries for this tenant
      queryClient.invalidateQueries({ queryKey: settingsKeys.tenant(variables.tenantId) });
      // Also invalidate the specific category query
      queryClient.invalidateQueries({
        queryKey: settingsKeys.category(variables.tenantId, variables.category),
      });
      showToast.success(`Categoría '${variables.category}' restablecida a valores predeterminados`);
    },
    onError: (error) => {
      console.error('Failed to reset category:', error);
      showToast.error('Error al restablecer la categoría');
    },
  });
};
