import React, { createContext, useContext, useEffect, useMemo } from 'react';

import { AnalyticsClient } from './analytics-client';

import type { AnalyticsConfig, AnalyticsContext } from './types';

const AnalyticsContextInstance = createContext<AnalyticsContext | null>(null);

interface AnalyticsProviderProps {
  config: AnalyticsConfig;
  children: React.ReactNode;
}

export const AnalyticsProvider: React.FC<AnalyticsProviderProps> = ({
  config,
  children,
}) => {
  const client = useMemo(() => new AnalyticsClient(config), [config]);

  useEffect(() => {
    return () => {
      client.destroy();
    };
  }, [client]);

  const contextValue: AnalyticsContext = useMemo(
    () => ({
      trackView: client.trackView.bind(client),
      trackEngagement: client.trackEngagement.bind(client),
      flush: client.flush.bind(client),
    }),
    [client],
  );

  return (
    <AnalyticsContextInstance.Provider value={contextValue}>
      {children}
    </AnalyticsContextInstance.Provider>
  );
};

export const useAnalytics = (): AnalyticsContext => {
  const context = useContext(AnalyticsContextInstance);
  if (!context) {
    throw new Error('useAnalytics must be used within an AnalyticsProvider');
  }
  return context;
};
