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

interface Module {
  id: string;
  name: string;
  description: string;
  concepts: string[];
  difficulty: 'beginner' | 'intermediate' | 'advanced';
}

interface LearningPath {
  id: string;
  name: string;
  description: string;
  modules: Module[];
}

interface LearningContextType {
  paths: LearningPath[];
  currentPath: string | null;
  currentModule: string | null;
  setCurrentPath: (pathId: string) => void;
  setCurrentModule: (moduleId: string) => void;
  loading: boolean;
  error: string | null;
}

const LearningContext = createContext<LearningContextType | undefined>(undefined);

export const LearningProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [paths, setPaths] = useState<LearningPath[]>([]);
  const [currentPath, setCurrentPath] = useState<string | null>(null);
  const [currentModule, setCurrentModule] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchPaths = async () => {
      try {
        const response = await fetch('/api/learning-paths');
        const data = await response.json();
        setPaths(data);
        setLoading(false);
      } catch (err) {
        setError('Failed to load learning paths');
        setLoading(false);
      }
    };

    fetchPaths();
  }, []);

  return (
    <LearningContext.Provider 
      value={{
        paths,
        currentPath,
        currentModule,
        setCurrentPath,
        setCurrentModule,
        loading,
        error
      }}
    >
      {children}
    </LearningContext.Provider>
  );
};

export const useLearning = () => {
  const context = useContext(LearningContext);
  if (context === undefined) {
    throw new Error('useLearning must be used within a LearningProvider');
  }
  return context;
};