import { createContext, useContext, useReducer, useEffect } from 'react';
import * as db from '../lib/db';
import { pb } from '../lib/pb';
import { getPersonalWeekNumber } from '../lib/curriculumService';

const AppContext = createContext();

const initialState = {
  currentUser: null,
  users: [],
  weekNumber: 0,
  isLoading: true
};

function computeWeekNumber(user) {
  if (!user || !user.curriculum_started_at || user.enrollment_status !== 'active') return 0;
  return getPersonalWeekNumber(user.curriculum_started_at);
}

function appReducer(state, action) {
  switch (action.type) {
    case 'INIT_APP':
      return {
        ...state,
        users: action.payload.users,
        isLoading: false
      };
    case 'LOGIN':
      return {
        ...state,
        currentUser: action.payload,
        weekNumber: computeWeekNumber(action.payload),
      };
    case 'UPDATE_CURRENT_USER':
      return {
        ...state,
        currentUser: action.payload,
        weekNumber: computeWeekNumber(action.payload),
        users: state.users.map(u => u.id === action.payload.id ? action.payload : u),
      };
    case 'LOGOUT':
      return { ...state, currentUser: null, weekNumber: 0 };
    default:
      return state;
  }
}

export function AppProvider({ children }) {
  const [state, dispatch] = useReducer(appReducer, initialState);

  useEffect(() => {
    const loadState = async () => {
      let members = await db.getTeamMembers();

      if (!members || members.length === 0) {
        try {
          const created = await db.addTeamMember({ name: 'Admin', role: 'admin', pin: '0000' });
          members = [created];
        } catch (e) {
          console.warn('[AppContext] Could not auto-create admin user:', e.message,
            '— Run scripts/setup-pb-collections.mjs to configure the database.');
        }
      }

      const sessionUserId = sessionStorage.getItem('respellion_session');
      if (sessionUserId) {
        const user = members.find(u => u.id === sessionUserId);
        if (user) {
          dispatch({ type: 'LOGIN', payload: user });
        }
      }

      dispatch({ type: 'INIT_APP', payload: { users: members } });
    };

    loadState().catch(console.error);
  }, []);

  const login = (userId, pin) => {
    const user = state.users.find(u => u.id === userId && u.pin === pin);
    if (user) {
      sessionStorage.setItem('respellion_session', user.id);
      dispatch({ type: 'LOGIN', payload: user });
      return true;
    }
    return false;
  };

  const logout = () => {
    sessionStorage.removeItem('respellion_session');
    dispatch({ type: 'LOGOUT' });
  };

  /**
   * Start the curriculum for the currently logged-in user.
   * Records the start timestamp and flips enrollment_status to 'active'.
   */
  const enrollCurrentUser = async () => {
    if (!state.currentUser) throw new Error('No user is logged in.');
    const startedAt = new Date().toISOString();
    const updated = await pb.collection('team_members').update(state.currentUser.id, {
      curriculum_started_at: startedAt,
      enrollment_status: 'active',
    });
    dispatch({ type: 'UPDATE_CURRENT_USER', payload: updated });
    return updated;
  };

  return (
    <AppContext.Provider value={{ state, dispatch, login, logout, enrollCurrentUser }}>
      {children}
    </AppContext.Provider>
  );
}

export function useApp() {
  return useContext(AppContext);
}
