import { useCallback, useEffect } from 'react';

import {
  getLocalStorageValueWith30DayExpiry,
  setLocalStorageValueWith30DayExpiry,
} from '@/utils/storage';

/**
 * Sprout affiliate tracking configuration
 */
const SPROUT_CONFIG = {
  STORAGE_KEY: 'tune_transaction_id',
  URL_PARAM: 'transaction_id',
} as const;

/**
 * Hook to manage Sprout affiliate tracking for content creator affiliate links.
 *
 * This hook provides methods to:
 * - Extract transaction_id from URL parameters
 * - Store and retrieve sprout_affiliate_id from localStorage
 * - Get the sprout_affiliate_id for API calls
 */
export const useSproutTracking = () => {
  /**
   * Extract transaction_id from URL parameters and store in localStorage
   * This should be called on page load to capture affiliate tracking
   */
  const initializeSproutTracking = useCallback(() => {
    if (typeof window === 'undefined') return;

    try {
      const urlParams = new URLSearchParams(window.location.search);
      const transactionId = urlParams.get(SPROUT_CONFIG.URL_PARAM);

      if (transactionId) {
        setLocalStorageValueWith30DayExpiry(
          SPROUT_CONFIG.STORAGE_KEY,
          transactionId
        );
        console.debug(
          `Sprout tracking initialized with transaction_id: ${transactionId}`
        );
      }
    } catch (error) {
      console.error('Error initializing Sprout tracking:', error);
    }
  }, []);

  /**
   * Get the current sprout_affiliate_id from localStorage
   * @returns The sprout affiliate ID or null if not found
   */
  const getSproutAffiliateId = useCallback((): string | null => {
    if (typeof window === 'undefined') return null;

    try {
      return getLocalStorageValueWith30DayExpiry(SPROUT_CONFIG.STORAGE_KEY);
    } catch (error) {
      console.error('Error getting Sprout affiliate ID:', error);
      return null;
    }
  }, []);

  /**
   * Get sprout_affiliate_id for API calls
   * This is the main method used by components to get the affiliate ID
   * @returns The sprout affiliate ID or undefined if not found
   */
  const getSproutAffiliateIdForApi = useCallback((): string | undefined => {
    const affiliateId = getSproutAffiliateId();
    return affiliateId && affiliateId.trim() !== '' ? affiliateId : undefined;
  }, [getSproutAffiliateId]);

  /**
   * Initialize tracking on mount if we're in a browser environment
   */
  useEffect(() => {
    initializeSproutTracking();
  }, [initializeSproutTracking]);

  return {
    getSproutAffiliateIdForApi,
  };
};
