import { useCallback } from 'react';
import { usePersSDK } from '../providers/PersSDKProvider';
/**
 * React hook for analytics operations in the PERS SDK
 *
 * Provides comprehensive analytics and business intelligence capabilities:
 * - **Transaction Analytics**: Volume, trends, business performance
 * - **Campaign Claim Analytics**: Campaign performance and claim patterns
 * - **User Analytics**: Engagement metrics with per-active-user averages
 * - **User Ranking**: Leaderboards with full user details
 * - **Business Ranking**: Business performance rankings
 * - **Retention Analytics**: Monthly retention metrics
 *
 * @returns Analytics hook with methods for data analysis
 *
 * @example Basic Transaction Analytics
 * ```typescript
 * function AnalyticsComponent() {
 *   const { getTransactionAnalytics } = useAnalytics();
 *
 *   const loadAnalytics = async () => {
 *     const analytics = await getTransactionAnalytics({
 *       startDate: '2024-01-01',
 *       endDate: '2024-01-31',
 *       groupBy: 'day'
 *     });
 *     console.log('Transaction analytics:', analytics);
 *   };
 * }
 * ```
 *
 * @example User Leaderboard
 * ```typescript
 * function LeaderboardScreen() {
 *   const { getUserRanking } = useAnalytics();
 *
 *   const loadLeaderboard = async () => {
 *     const ranking = await getUserRanking({
 *       sortBy: 'totalTransactions',
 *       sortOrder: 'DESC',
 *       limit: 50
 *     });
 *     ranking.results.forEach((user, i) => {
 *       console.log(`#${i + 1}: ${user.email} - ${user.totalTransactions} txns`);
 *     });
 *   };
 * }
 * ```
 */
export const useAnalytics = () => {
    const { sdk, isInitialized } = usePersSDK();
    /**
     * Retrieves transaction analytics data based on request parameters
     *
     * @param request - Analytics request parameters (time range, grouping, filters, etc.)
     * @returns Promise resolving to analytics data with results and metadata
     * @throws Error if SDK is not initialized
     *
     * @example
     * ```typescript
     * const analytics = await getTransactionAnalytics({
     *   startDate: '2024-01-01',
     *   endDate: '2024-01-31',
     *   groupBy: 'day',
     *   metrics: ['count', 'sum']
     * });
     * ```
     */
    const getTransactionAnalytics = useCallback(async (request) => {
        if (!isInitialized || !sdk) {
            throw new Error('SDK not initialized. Call initialize() first.');
        }
        try {
            const result = await sdk.analytics.getTransactionAnalytics(request);
            return result;
        }
        catch (error) {
            console.error('Failed to fetch transaction analytics:', error);
            throw error;
        }
    }, [sdk, isInitialized]);
    /**
     * Retrieves campaign claim analytics with aggregation
     *
     * Provides insights into campaign performance, claim patterns, and user engagement.
     *
     * @param request - Analytics request with filters, groupBy, and metrics
     * @returns Promise resolving to campaign claim analytics data
     *
     * @example Claims per campaign
     * ```typescript
     * const analytics = await getCampaignClaimAnalytics({
     *   filters: { status: 'COMPLETED' },
     *   groupBy: ['campaignId'],
     *   metrics: ['count'],
     *   sortBy: 'count',
     *   sortOrder: 'DESC',
     *   limit: 10
     * });
     * console.log('Top campaigns:', analytics.results);
     * ```
     */
    const getCampaignClaimAnalytics = useCallback(async (request) => {
        if (!isInitialized || !sdk) {
            throw new Error('SDK not initialized. Call initialize() first.');
        }
        try {
            const result = await sdk.analytics.getCampaignClaimAnalytics(request);
            return result;
        }
        catch (error) {
            console.error('Failed to fetch campaign claim analytics:', error);
            throw error;
        }
    }, [sdk, isInitialized]);
    /**
     * Retrieves user analytics with engagement metrics
     *
     * Includes both per-user and per-active-user metrics for accurate engagement insights.
     * Per-active-user metrics show concentrated engagement among active users.
     *
     * @param request - Analytics request with optional filters and date range
     * @returns Promise resolving to user analytics data
     *
     * @example Compare per-user vs per-active-user metrics
     * ```typescript
     * const analytics = await getUserAnalytics({
     *   startDate: new Date('2026-02-01'),
     *   endDate: new Date('2026-02-28')
     * });
     *
     * console.log(`Active users: ${analytics.activeUsers} / ${analytics.totalUsers}`);
     * console.log(`Engagement rate: ${analytics.engagementRate.toFixed(1)}%`);
     *
     * // Per-active-user metrics (more meaningful)
     * console.log(`Avg transactions per active user: ${analytics.averageTransactionsPerActiveUser}`);
     * ```
     *
     * @example Business-specific analytics
     * ```typescript
     * const analytics = await getUserAnalytics({
     *   filters: { businessId: 'business-123' },
     *   startDate: new Date('2026-01-01'),
     *   endDate: new Date('2026-12-31')
     * });
     * ```
     */
    const getUserAnalytics = useCallback(async (request = {}) => {
        if (!isInitialized || !sdk) {
            throw new Error('SDK not initialized. Call initialize() first.');
        }
        try {
            const result = await sdk.analytics.getUserAnalytics(request);
            return result;
        }
        catch (error) {
            console.error('Failed to fetch user analytics:', error);
            throw error;
        }
    }, [sdk, isInitialized]);
    /**
     * Retrieves user transaction ranking with enriched user data
     *
     * Returns ranked list of users with full user details (email, externalUserId)
     * and transaction metrics. Ideal for leaderboards, engagement analysis,
     * and identifying power users.
     *
     * @param request - Ranking request with filters, sorting, and limit
     * @returns Promise resolving to ranked user list with transaction metrics
     *
     * @example Top 50 users by transaction count
     * ```typescript
     * const ranking = await getUserRanking({
     *   sortBy: 'totalTransactions',
     *   sortOrder: 'DESC',
     *   limit: 50
     * });
     *
     * ranking.results.forEach((user, index) => {
     *   console.log(`#${index + 1}: ${user.email || user.externalUserId}`);
     *   console.log(`  Transactions: ${user.totalTransactions}`);
     *   console.log(`  Token spent: ${user.tokenSpent}`);
     * });
     * ```
     *
     * @example Top STAMP spenders
     * ```typescript
     * const ranking = await getUserRanking({
     *   filters: { tokenType: 'STAMP' },
     *   sortBy: 'tokenSpent',
     *   sortOrder: 'DESC',
     *   limit: 20
     * });
     * ```
     */
    const getUserRanking = useCallback(async (request = {}) => {
        if (!isInitialized || !sdk) {
            throw new Error('SDK not initialized. Call initialize() first.');
        }
        try {
            const result = await sdk.analytics.getUserRanking(request);
            return result;
        }
        catch (error) {
            console.error('Failed to fetch user ranking:', error);
            throw error;
        }
    }, [sdk, isInitialized]);
    /**
     * Retrieves business transaction ranking with enriched business data
     *
     * Returns ranked list of businesses with transaction metrics for
     * partner analytics and performance dashboards.
     *
     * @param request - Ranking request with filters, sorting, and limit
     * @returns Promise resolving to ranked business list
     *
     * @example Top businesses by transaction count
     * ```typescript
     * const ranking = await getBusinessRanking({
     *   sortBy: 'totalTransactions',
     *   sortOrder: 'DESC',
     *   limit: 20
     * });
     *
     * ranking.results.forEach((business, index) => {
     *   console.log(`#${index + 1}: ${business.businessId}`);
     *   console.log(`  Transactions: ${business.totalTransactions}`);
     *   console.log(`  Token spent: ${business.tokenSpent}`);
     * });
     * ```
     */
    const getBusinessRanking = useCallback(async (request = {}) => {
        if (!isInitialized || !sdk) {
            throw new Error('SDK not initialized. Call initialize() first.');
        }
        try {
            const result = await sdk.analytics.getBusinessRanking(request);
            return result;
        }
        catch (error) {
            console.error('Failed to fetch business ranking:', error);
            throw error;
        }
    }, [sdk, isInitialized]);
    /**
     * Retrieves monthly user retention analytics
     *
     * Returns monthly retention data with active, new, and returning users
     * along with retention rates. Useful for churn analysis and engagement trends.
     *
     * @param request - Retention request with monthsBack and filters
     * @returns Promise resolving to monthly retention data
     *
     * @example Get 12 months of retention data
     * ```typescript
     * const retention = await getRetentionAnalytics({
     *   monthsBack: 12
     * });
     *
     * retention.results.forEach(month => {
     *   console.log(`${month.month}:`);
     *   console.log(`  Active: ${month.activeUsers}`);
     *   console.log(`  New: ${month.newUsers}`);
     *   console.log(`  Returning: ${month.returningUsers}`);
     *   console.log(`  Retention Rate: ${month.retentionRate.toFixed(1)}%`);
     * });
     * ```
     */
    const getRetentionAnalytics = useCallback(async (request = {}) => {
        if (!isInitialized || !sdk) {
            throw new Error('SDK not initialized. Call initialize() first.');
        }
        try {
            const result = await sdk.analytics.getRetentionAnalytics(request);
            return result;
        }
        catch (error) {
            console.error('Failed to fetch retention analytics:', error);
            throw error;
        }
    }, [sdk, isInitialized]);
    return {
        getTransactionAnalytics,
        getCampaignClaimAnalytics,
        getUserAnalytics,
        getUserRanking,
        getBusinessRanking,
        getRetentionAnalytics,
        isAvailable: isInitialized && !!sdk?.analytics,
    };
};
