import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import { Study } from '../types';
import { apiClient } from '../api/client';

interface StudyContextType {
  selectedStudy: Study | null;
  setSelectedStudy: (study: Study | null) => void;
  studies: Study[];
  refreshStudies: () => Promise<void>;
  isLoading: boolean;
  isInitialized: boolean; // True once initial load + localStorage restoration is complete
  clearStudy: () => void;
}

const StudyContext = createContext<StudyContextType | undefined>(undefined);

export const StudyProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
  const [selectedStudy, setSelectedStudyState] = useState<Study | null>(null);
  const [studies, setStudies] = useState<Study[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isInitialized, setIsInitialized] = useState(false);

  const refreshStudies = async () => {
    try {
      setIsLoading(true);
      const response = await apiClient.getStudies();
      setStudies(response.studies);

      // If we have a selected study, refresh its data
      if (selectedStudy) {
        const updated = response.studies.find(s => s.id === selectedStudy.id);
        if (updated) {
          setSelectedStudyState(updated);
        }
      }
    } catch (error) {
      console.error('Failed to fetch studies:', error);
    } finally {
      setIsLoading(false);
    }
  };

  const setSelectedStudy = (study: Study | null) => {
    setSelectedStudyState(study);
    if (study) {
      localStorage.setItem('selectedStudyId', study.id);
    } else {
      localStorage.removeItem('selectedStudyId');
    }
  };

  const clearStudy = () => {
    setSelectedStudyState(null);
    localStorage.removeItem('selectedStudyId');
  };

  // Initial load
  useEffect(() => {
    const init = async () => {
      try {
        console.log('[StudyContext] Fetching studies...');
        const response = await apiClient.getStudies();
        console.log('[StudyContext] Got studies:', response.studies.length, response.studies);
        setStudies(response.studies);

        // Restore last selected study from localStorage
        const lastStudyId = localStorage.getItem('selectedStudyId');
        if (lastStudyId) {
          const study = response.studies.find(s => s.id === lastStudyId);
          if (study) {
            setSelectedStudyState(study);
          }
        }
      } catch (error) {
        console.error('[StudyContext] Failed to initialize studies:', error);
      } finally {
        console.log('[StudyContext] Initialization complete, isLoading=false');
        setIsLoading(false);
        setIsInitialized(true); // Mark as initialized AFTER localStorage restoration
      }
    };
    init();
  }, []);

  return (
    <StudyContext.Provider value={{
      selectedStudy,
      setSelectedStudy,
      studies,
      refreshStudies,
      isLoading,
      isInitialized,
      clearStudy
    }}>
      {children}
    </StudyContext.Provider>
  );
};

export const useStudy = () => {
  const context = useContext(StudyContext);
  if (context === undefined) {
    throw new Error('useStudy must be used within a StudyProvider');
  }
  return context;
};
