import { useCallback, useState } from 'react';
import { useAmplitude } from 'src/contexts/amplitudeContext/amplitudeContext';
import { SpiffyMetricsEventName } from 'src/services/amplitudeService/amplitudeService';

export const useAmplitudeTracking = () => {
  const { trackEvent, isReady } = useAmplitude();
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<Error | null>(null);

  const track = useCallback(
    async (eventName: SpiffyMetricsEventName, eventProps?: Record<string, unknown>) => {
      if (!isReady) return;

      setLoading(true);
      setError(null);

      try {
        await trackEvent({ eventName, eventProps });
      } catch (err) {
        setError(err instanceof Error ? err : new Error('Tracking failed'));
        throw err;
      } finally {
        setLoading(false);
      }
    },
    [trackEvent, isReady],
  );

  return { track, loading, error, isReady };
};
