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

const AppContext = createContext();

const initialState = {
  currentUser: null,
  users: [],
  weekNumber: getWeekNumber(new Date()),
  isLoading: true
};

function appReducer(state, action) {
  switch (action.type) {
    case 'INIT_APP':
      return {
        ...state,
        users: action.payload.users,
        weekNumber: action.payload.weekNumber || state.weekNumber,
        isLoading: false
      };
    case 'LOGIN':
      return { ...state, currentUser: action.payload };
    case 'LOGOUT':
      return { ...state, currentUser: null };
    case 'ADVANCE_WEEK':
      return { ...state, weekNumber: state.weekNumber + 1 };
    default:
      return state;
  }
}

function getWeekNumber(d) {
  d = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()));
  d.setUTCDate(d.getUTCDate() + 4 - (d.getUTCDay()||7));
  const yearStart = new Date(Date.UTC(d.getUTCFullYear(),0,1));
  return Math.ceil(( ( (d - yearStart) / 86400000) + 1)/7);
}

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 storedWeek = getWeekNumber(new Date());

      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, weekNumber: storedWeek } });
    };

    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' });
  };

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

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