
import React, { createContext, useContext, useState, useEffect } from 'react';
import { useAuth } from '@/contexts/AuthContext';
import { supabase } from '@/integrations/supabase/client';

const AssociationContext = createContext(null);

export function AssociationProvider({ children }) {
  const { userRole, isStaff } = useAuth();
  
  const [selectedAssociation, setSelectedAssociation] = useState(() => {
    const saved = localStorage.getItem('selectedAssociation');
    return saved ? JSON.parse(saved) : null;
  });
  
  const [associations, setAssociations] = useState([]);
  const [loadingAssociations, setLoadingAssociations] = useState(true);

  useEffect(() => {
    if (selectedAssociation) {
      localStorage.setItem('selectedAssociation', JSON.stringify(selectedAssociation));
    } else {
      localStorage.removeItem('selectedAssociation');
    }
  }, [selectedAssociation]);

  useEffect(() => {
    const fetchAssociations = async () => {
      setLoadingAssociations(true);
      try {
        if (!userRole) return;
        
        let query = supabase.from('associations').select('id, name').order('name');
        
        // Admins and employees do NOT require association; clients/board members require association.
        if (!isStaff && userRole.client_id) {
          query = query.eq('id', userRole.client_id);
        }
        
        const { data, error } = await query;
        if (error) throw error;
        
        setAssociations(data || []);
        
        // Auto-select first association if none selected or if current is invalid
        if (data && data.length > 0) {
          if (!selectedAssociation) {
            setSelectedAssociation(data[0]);
          } else if (!data.find(d => d.id === selectedAssociation.id)) {
            setSelectedAssociation(data[0]);
          }
        } else if (data && data.length === 0) {
          setSelectedAssociation(null);
        }
      } catch (error) {
        console.error('Failed to fetch associations:', error);
      } finally {
        setLoadingAssociations(false);
      }
    };

    fetchAssociations();
  }, [userRole, isStaff]);

  return (
    <AssociationContext.Provider 
      value={{ 
        selectedAssociation, 
        setSelectedAssociation, 
        associations,
        loadingAssociations 
      }}
    >
      {children}
    </AssociationContext.Provider>
  );
}

export const useAssociation = () => {
  const ctx = useContext(AssociationContext);
  if (ctx) return ctx;
  // Fallback when no provider is mounted: read selection from localStorage.
  try {
    const saved = JSON.parse(localStorage.getItem('selectedAssociation') || 'null');
    return {
      selectedAssociation: saved,
      setSelectedAssociation: (next) => {
        if (next) localStorage.setItem('selectedAssociation', JSON.stringify(next));
        else localStorage.removeItem('selectedAssociation');
      },
      associations: saved ? [saved] : [],
      loadingAssociations: false,
    };
  } catch {
    return { selectedAssociation: null, setSelectedAssociation: () => {}, associations: [], loadingAssociations: false };
  }
};
