import { createContext, useContext, useEffect, useState } from 'react';
import { createHousehold as createHouseholdApi, getUserHouseholds } from '../api/households';
import { AuthContext } from './AuthContext';

export const HouseholdContext = createContext({
  households: [],
  activeHousehold: null,
  loading: false,
  error: null,
  setActiveHousehold: () => { },
  refreshHouseholds: () => { },
  createHousehold: () => { },
});

export const HouseholdProvider = ({ children }) => {
  const { token } = useContext(AuthContext);
  const [households, setHouseholds] = useState([]);
  const [activeHousehold, setActiveHouseholdState] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  // Load households on mount and when token changes
  useEffect(() => {
    if (token) {
      loadHouseholds();
    } else {
      // Clear state when logged out
      setHouseholds([]);
      setActiveHouseholdState(null);
    }
  }, [token]);

  // Load active household from localStorage on mount
  useEffect(() => {
    if (households.length === 0) return;

    console.log('[HouseholdContext] Setting active household from:', households);
    const savedHouseholdId = localStorage.getItem('activeHouseholdId');
    if (savedHouseholdId) {
      const household = households.find(h => h.id === parseInt(savedHouseholdId));
      if (household) {
        console.log('[HouseholdContext] Found saved household:', household);
        setActiveHouseholdState(household);
        return;
      }
    }

    // No saved household or not found, use first one
    console.log('[HouseholdContext] Using first household:', households[0]);
    setActiveHouseholdState(households[0]);
    localStorage.setItem('activeHouseholdId', households[0].id);
  }, [households]);

  const loadHouseholds = async () => {
    if (!token) return;

    setLoading(true);
    setError(null);
    try {
      console.log('[HouseholdContext] Loading households...');
      const response = await getUserHouseholds();
      console.log('[HouseholdContext] Loaded households:', response.data);
      setHouseholds(response.data);
    } catch (err) {
      console.error('[HouseholdContext] Failed to load households:', err);
      setError(err.response?.data?.message || 'Failed to load households');
      setHouseholds([]);
    } finally {
      setLoading(false);
    }
  };

  const setActiveHousehold = (household) => {
    setActiveHouseholdState(household);
    if (household) {
      localStorage.setItem('activeHouseholdId', household.id);
    } else {
      localStorage.removeItem('activeHouseholdId');
    }
  };

  const createHousehold = async (name) => {
    try {
      const response = await createHouseholdApi(name);
      const newHousehold = response.data.household;

      // Refresh households list
      await loadHouseholds();

      // Set new household as active
      setActiveHousehold(newHousehold);

      return newHousehold;
    } catch (err) {
      console.error('Failed to create household:', err);
      throw err;
    }
  };

  const value = {
    households,
    activeHousehold,
    loading,
    error,
    setActiveHousehold,
    refreshHouseholds: loadHouseholds,
    createHousehold,
  };

  return (
    <HouseholdContext.Provider value={value}>
      {children}
    </HouseholdContext.Provider>
  );
};
