'use client';

import React, { useCallback } from 'react';
import { useWorkoutTracking } from '@/app/hooks/useWorkoutTracking';
import { WorkoutSession, CardioSession, NutritionLog } from '@/app/lib/storage/workoutStorage';

export interface WorkoutDataIntegrationProps {
  onSave?: (data: any) => void;
  autoSave?: boolean;
}

/**
 * WorkoutDataIntegration component that provides workout tracking context
 * Use this component to wrap sections that need to save workout data
 */
export const WorkoutDataIntegration: React.FC<{
  children: React.ReactNode;
} & WorkoutDataIntegrationProps> = ({ children, onSave, autoSave = true }) => {
  const { metrics, addWorkoutSession, addCardioSession, addNutritionLog, refreshMetrics } =
    useWorkoutTracking();

  const handleWorkoutSave = useCallback(
    (session: WorkoutSession) => {
      addWorkoutSession(session);
      if (onSave) onSave({ type: 'workout', data: session });
    },
    [addWorkoutSession, onSave]
  );

  const handleCardioSave = useCallback(
    (session: CardioSession) => {
      addCardioSession(session);
      if (onSave) onSave({ type: 'cardio', data: session });
    },
    [addCardioSession, onSave]
  );

  const handleNutritionSave = useCallback(
    (log: NutritionLog) => {
      addNutritionLog(log);
      if (onSave) onSave({ type: 'nutrition', data: log });
    },
    [addNutritionLog, onSave]
  );

  // Expose save functions via context or props
  const contextValue = {
    metrics,
    handleWorkoutSave,
    handleCardioSave,
    handleNutritionSave,
    refreshMetrics,
    autoSave,
  };

  // Clone children and pass context data as props
  return (
    <div data-workout-integration="true" data-context={JSON.stringify(contextValue)}>
      {children}
    </div>
  );
};

export default WorkoutDataIntegration;
