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>;
  updateState: (state: Partial<TimerState>) => Promise<void>;
}

// Default context values
const defaultContextValue: TimerContextType = {
  timerState: {
    reps: 1,
    workTime: 0,
    restTime: 0
  },
  isLoading: true,
  updateReps: async () => {},
  updateWorkTime: async () => {},
  updateRestTime: 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
  });
  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);
    }
  };

  // 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,
    updateState
  };

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