import { useState, useEffect } from 'react';
import { useAuth } from '@/lib/auth/AuthContext';

const SELECTED_FAMILY_KEY = 'selectedFamilyIndex';

/**
 * Hook to manage selected family across the app
 * Stores selection in localStorage for persistence
 */
export function useSelectedFamily() {
  const { user } = useAuth();
  const userFamilies = user?.families || [];

  // Initialize from localStorage or default to 0
  const [selectedIndex, setSelectedIndex] = useState<number>(() => {
    if (typeof window === 'undefined') return 0;
    const stored = localStorage.getItem(SELECTED_FAMILY_KEY);
    return stored ? parseInt(stored, 10) : 0;
  });

  // Ensure selectedIndex is within bounds
  useEffect(() => {
    if (selectedIndex >= userFamilies.length && userFamilies.length > 0) {
      setSelectedIndex(0);
    }
  }, [userFamilies.length, selectedIndex]);

  // Save to localStorage when changed
  const setSelectedFamily = (index: number) => {
    setSelectedIndex(index);
    if (typeof window !== 'undefined') {
      localStorage.setItem(SELECTED_FAMILY_KEY, index.toString());
    }
  };

  const familyId = userFamilies[selectedIndex]?.familyId || null;
  const familyRole = userFamilies[selectedIndex]?.role || null;

  return {
    familyId,
    familyRole,
    selectedIndex,
    setSelectedIndex: setSelectedFamily,
    userFamilies,
    hasMultipleFamilies: userFamilies.length > 1,
  };
}
