import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import { timerStore, TimerState } from './TimerStore';

// Context interface
interface TimerContextType {
  timerState: TimerState;
  isLoading: boolean;
  updateReps: (reps: number) => Promise<void>;
  updateWorkTime: (workTime: number) => Promise<void>;
  updateRestTime: (restTime: number) => Promise<void>;
  updatePreparationTime: (preparationTime: number) => Promise<void>;
  updateState: (state: Partial<TimerState>) => Promise<void>;
}

// Default context values
const defaultContextValue: TimerContextType = {
  timerState: {
    reps: 1,
    workTime: 0,
    restTime: 0,
    preparationTime: 3
  },
  isLoading: true,
  updateReps: async () => {},
  updateWorkTime: async () => {},
  updateRestTime: async () => {},
  updatePreparationTime: async () => {},
  updateState: async () => {}
};

// Context creation
const TimerContext = createContext<TimerContextType>(defaultContextValue);

// Custom hook to use the context
export const useTimerContext = () => useContext(TimerContext);

// Provider props
interface TimerProviderProps {
  children: ReactNode;
}

// Provider component
export const TimerProvider: React.FC<TimerProviderProps> = ({ children }) => {
  const [timerState, setTimerState] = useState<TimerState>({
    reps: 1,
    workTime: 0,
    restTime: 0,
    preparationTime: 3
  });
  const [isLoading, setIsLoading] = useState(true);

  // Load data on startup
  useEffect(() => {
    const loadData = async () => {
      try {
        const state = await timerStore.getState();
        setTimerState(state);
      } catch (error) {
        console.error('Error loading data:', error);
      } finally {
        setIsLoading(false);
      }
    };

    loadData();
  }, []);

  // Update repetitions
  const updateReps = async (reps: number) => {
    try {
      await timerStore.saveReps(reps);
      setTimerState(prev => ({ ...prev, reps }));
    } catch (error) {
      console.error('Error updating repetitions:', error);
    }
  };

	const updatePreparationTime = async (preparationTime: number) => {
		try {
			await timerStore.savePreparationTime(preparationTime);
			setTimerState(prev => ({ ...prev, preparationTime }));
		} catch (error) {
			console.error('Error updating preparation time:', error);
		}
	}
  // Update work time
  const updateWorkTime = async (workTime: number) => {
    try {
      await timerStore.saveWorkTime(workTime);
      setTimerState(prev => ({ ...prev, workTime }));
    } catch (error) {
      console.error('Error updating work time:', error);
    }
  };

  // Update rest time
  const updateRestTime = async (restTime: number) => {
    try {
      await timerStore.saveRestTime(restTime);
      setTimerState(prev => ({ ...prev, restTime }));
    } catch (error) {
      console.error('Error updating rest time:', error);
    }
  };

  // Update multiple values at once
  const updateState = async (state: Partial<TimerState>) => {
    try {
      const newState = { ...timerState, ...state };
      await timerStore.saveState(newState);
      setTimerState(newState);
    } catch (error) {
      console.error('Error updating state:', error);
    }
  };

  const contextValue: TimerContextType = {
    timerState,
    isLoading,
    updateReps,
    updateWorkTime,
    updateRestTime,
    updatePreparationTime,
    updateState
  };

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