import React, { createContext, useContext, useState } from 'react';

interface UserState {
  isAuthenticated: boolean;
  username: string | null;
  progress: {
    completedModules: string[];
    achievements: Array<{
      name: string;
      date: string;
      description: string;
    }>;
    learningStreak: number;
  };
}

interface UserContextType {
  user: UserState;
  login: (username: string) => void;
  logout: () => void;
  updateProgress: (moduleId: string) => void;
}

const defaultUserState: UserState = {
  isAuthenticated: false,
  username: null,
  progress: {
    completedModules: [],
    achievements: [],
    learningStreak: 0
  }
};

const UserContext = createContext<UserContextType | undefined>(undefined);

export const UserProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [user, setUser] = useState<UserState>(defaultUserState);

  const login = (username: string) => {
    setUser({
      isAuthenticated: true,
      username,
      progress: {
        ...defaultUserState.progress
      }
    });
  };

  const logout = () => {
    setUser(defaultUserState);
  };

  const updateProgress = (moduleId: string) => {
    setUser(prev => ({
      ...prev,
      progress: {
        ...prev.progress,
        completedModules: [...prev.progress.completedModules, moduleId]
      }
    }));
  };

  return (
    <UserContext.Provider value={{ user, login, logout, updateProgress }}>
      {children}
    </UserContext.Provider>
  );
};

export const useUser = () => {
  const context = useContext(UserContext);
  if (context === undefined) {
    throw new Error('useUser must be used within a UserProvider');
  }
  return context;
};