import React, { createContext, useReducer, useCallback, useMemo, useEffect, useRef } from 'react';
import { AuthContextType, AuthState, LoginCredentials, SignupCredentials, AuthError, User } from '../../types/auth.types';
import { AuthService } from '../../services/authService';
import { ErrorBoundary } from '../common/ErrorBoundary';

const ACTIVITY_TIMEOUT = 30 * 60 * 1000; // 30 minutes
const REFRESH_INTERVAL = 5 * 60 * 1000; // 5 minutes

const initialState: AuthState = {
  user: null,
  isAuthenticated: false,
  isLoading: true,
  error: null,
  lastActivity: new Date(),
};

export const AuthContext = createContext<AuthContextType | undefined>(undefined);

type AuthAction =
  | { type: 'AUTH_START' }
  | { type: 'AUTH_SUCCESS'; payload: User }
  | { type: 'AUTH_FAILURE'; payload: AuthError }
  | { type: 'CLEAR_ERROR' }
  | { type: 'LOGOUT' }
  | { type: 'UPDATE_USER'; payload: Partial<User> }
  | { type: 'UPDATE_LAST_ACTIVITY' };

const authReducer = (state: AuthState, action: AuthAction): AuthState => {
  switch (action.type) {
    case 'AUTH_START':
      return { ...state, isLoading: true, error: null };
    case 'AUTH_SUCCESS':
      return {
        ...state,
        isLoading: false,
        isAuthenticated: true,
        user: action.payload,
        error: null,
        lastActivity: new Date(),
      };
    case 'AUTH_FAILURE':
      return {
        ...state,
        isLoading: false,
        isAuthenticated: false,
        error: action.payload,
      };
    case 'CLEAR_ERROR':
      return { ...state, error: null };
    case 'LOGOUT':
      return { ...initialState, isLoading: false };
    case 'UPDATE_USER':
      return {
        ...state,
        user: state.user ? { ...state.user, ...action.payload } : null,
      };
    case 'UPDATE_LAST_ACTIVITY':
      return { ...state, lastActivity: new Date() };
    default:
      return state;
  }
};

export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [state, dispatch] = useReducer(authReducer, initialState);
  const activityTimeoutRef = useRef<NodeJS.Timeout>();
  const refreshTokenIntervalRef = useRef<NodeJS.Timeout>();

  // ... rest of the component with similar improvements ...

  return (
    <ErrorBoundary>
      <AuthContext.Provider value={value}>{children}</AuthContext.Provider>
    </ErrorBoundary>
  );
};

AuthProvider.displayName = 'AuthProvider';