import { useState, useEffect } from 'react';
import { WorkoutSession, WorkoutPlan, ExerciseDef } from '../types';

interface UsePlanExecutionProps {
    activeSession: WorkoutSession | null;
    activePlan: WorkoutPlan | null;
    exercises: ExerciseDef[];
}

export const usePlanExecution = ({ activeSession, activePlan, exercises }: UsePlanExecutionProps) => {
    const [currentStepIndex, setCurrentStepIndex] = useState(0);
    const [showPlanPrep, setShowPlanPrep] = useState<WorkoutPlan | null>(null);
    const [showPlanList, setShowPlanList] = useState(false);

    // Automatically determine current step based on logged sets vs plan
    useEffect(() => {
        if (activeSession && activePlan) {
            const performedCounts = new Map<string, number>();
            for (const set of activeSession.sets) {
                performedCounts.set(set.exerciseId, (performedCounts.get(set.exerciseId) || 0) + 1);
            }

            let nextStepIndex = activePlan.steps.length; // Default to finished
            const plannedCounts = new Map<string, number>();
            for (let i = 0; i < activePlan.steps.length; i++) {
                const step = activePlan.steps[i];
                const exerciseId = step.exerciseId;
                plannedCounts.set(exerciseId, (plannedCounts.get(exerciseId) || 0) + 1);
                const performedCount = performedCounts.get(exerciseId) || 0;

                if (performedCount < plannedCounts.get(exerciseId)!) {
                    nextStepIndex = i;
                    break;
                }
            }
            setCurrentStepIndex(nextStepIndex);
        }
    }, [activeSession, activePlan]);

    const getCurrentStep = () => {
        if (activeSession && activePlan && activePlan.steps.length > 0) {
            if (currentStepIndex < activePlan.steps.length) {
                return activePlan.steps[currentStepIndex];
            }
        }
        return null;
    };

    const jumpToStep = (index: number) => {
        if (!activePlan) return;
        setCurrentStepIndex(index);
        setShowPlanList(false);
    };

    return {
        currentStepIndex,
        setCurrentStepIndex,
        showPlanPrep,
        setShowPlanPrep,
        showPlanList,
        setShowPlanList,
        getCurrentStep,
        jumpToStep
    };
};
