/**
 * Advanced Settings React Query Hooks
 *
 * @module Support/hooks
 * @since 1.0.0
 */

import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import apiFetch from '@wordpress/api-fetch';
import type {
  AdvancedSettings,
  ImportResult,
  ExportResponse,
  CompetitorSource
} from '../types/advanced-settings';
import { advancedSettingsDefaults, safeValidateAdvancedSettings } from '../types/advanced-settings';

const QUERY_KEY = ['prorank', 'advanced-settings'] as const;
const STALE_TIME = 5 * 60 * 1000; // 5 minutes

/**
 * Fetch advanced settings from API
 */
async function fetchAdvancedSettings(): Promise<AdvancedSettings> {
  const response = await apiFetch<{ data?: Partial<AdvancedSettings> }>({
    path: '/prorank-seo/v1/advanced-settings',
    method: 'GET',
  });

  const result = safeValidateAdvancedSettings({
    ...advancedSettingsDefaults,
    ...response?.data,
  });

  if (!result.success) {
    console.warn('Advanced settings validation failed:', result.error);
    return advancedSettingsDefaults;
  }

  return result.data;
}

/**
 * Save advanced settings to API
 */
async function saveAdvancedSettings(settings: AdvancedSettings): Promise<{ success: boolean }> {
  return apiFetch({
    path: '/prorank-seo/v1/advanced-settings',
    method: 'POST',
    data: { advanced: settings },
  });
}

/**
 * Clear all caches
 */
async function clearCache(): Promise<{ success: boolean; message?: string }> {
  return apiFetch({
    path: '/prorank-seo/v1/cache/clear',
    method: 'POST',
  });
}

/**
 * Export all settings
 */
async function exportSettings(): Promise<ExportResponse> {
  return apiFetch({
    path: '/prorank-seo/v1/import-export/export?type=all',
    method: 'GET',
  });
}

/**
 * Import settings from file
 */
async function importSettings(data: unknown): Promise<{ success: boolean; message?: string }> {
  const encodedData = window.btoa(JSON.stringify(data));

  return apiFetch({
    path: '/prorank-seo/v1/import-export/import',
    method: 'POST',
    data: {
      data: encodedData,
      type: 'all',
    },
  });
}

/**
 * Import from competitor plugin
 */
async function importFromCompetitor(
  source: CompetitorSource,
  types: string[] = ['meta', 'settings', 'redirects', 'schema', 'locations']
): Promise<ImportResult> {
  return apiFetch({
    path: '/prorank-seo/v1/import-export/competitor',
    method: 'POST',
    data: { source, types },
  });
}

/**
 * Hook to fetch advanced settings
 */
export function useAdvancedSettings() {
  return useQuery({
    queryKey: QUERY_KEY,
    queryFn: fetchAdvancedSettings,
    staleTime: STALE_TIME,
    gcTime: 10 * 60 * 1000, // 10 minutes
  });
}

/**
 * Hook to save advanced settings
 */
export function useSaveAdvancedSettings() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: saveAdvancedSettings,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: QUERY_KEY });
    },
  });
}

/**
 * Hook to clear cache
 */
export function useClearCache() {
  return useMutation({
    mutationFn: clearCache,
  });
}

/**
 * Hook to export settings
 */
export function useExportSettings() {
  return useMutation({
    mutationFn: exportSettings,
    onSuccess: (data) => {
      const decoded = window.atob(data.data);
      const blob = new Blob([decoded], { type: 'application/json' });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = data.filename || `prorank-settings-${new Date().toISOString().split('T')[0]}.json`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
    },
  });
}

/**
 * Hook to import settings from file
 */
export function useImportSettings() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: importSettings,
    onSuccess: () => {
      queryClient.invalidateQueries();
    },
  });
}

/**
 * Hook to import from competitor
 */
export function useImportFromCompetitor() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: ({ source, types }: { source: CompetitorSource; types?: string[] }) =>
      importFromCompetitor(source, types),
    onSuccess: () => {
      queryClient.invalidateQueries();
    },
  });
}
