import { useState, useCallback } from 'react';
import { supabase } from '@/integrations/supabase/client';
import { useToast } from '@/hooks/use-toast';

export function useAssociationBoardMembers() {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const { toast } = useToast();

  const fetchBoardMembers = useCallback(async (clientId) => {
    setLoading(true);
    try {
      const { data, error } = await supabase
        .from('association_board_members')
        .select(`
          user_id,
          users (
            id,
            email,
            full_name
          )
        `)
        .eq('client_id', clientId);

      if (error) throw error;
      
      return data.map(item => item.users).filter(Boolean);
    } catch (err) {
      console.error('Error fetching board members:', err);
      setError(err.message);
      return [];
    } finally {
      setLoading(false);
    }
  }, []);

  const fetchAvailableUsers = useCallback(async () => {
    setLoading(true);
    try {
      const { data, error } = await supabase
        .from('users')
        .select('id, email, full_name, client_id, role')
        .eq('role', 'client') 
        .order('email');

      if (error) throw error;
      return data;
    } catch (err) {
      console.error('Error fetching available users:', err);
      setError(err.message);
      return [];
    } finally {
      setLoading(false);
    }
  }, []);

  const saveBoardMembers = useCallback(async (clientId, selectedUserIds) => {
    setLoading(true);
    try {
      const { data: current, error: fetchError } = await supabase
        .from('association_board_members')
        .select('user_id')
        .eq('client_id', clientId);
      
      if (fetchError) throw fetchError;
      
      const currentUserIds = current.map(c => c.user_id);

      const toAdd = selectedUserIds.filter(id => !currentUserIds.includes(id));
      const toRemove = currentUserIds.filter(id => !selectedUserIds.includes(id));

      if (toRemove.length > 0) {
        const { error: removeError } = await supabase
          .from('association_board_members')
          .delete()
          .eq('client_id', clientId)
          .in('user_id', toRemove);
        if (removeError) throw removeError;
      }

      if (toAdd.length > 0) {
        const { error: addError } = await supabase
          .from('association_board_members')
          .insert(toAdd.map(userId => ({
            client_id: clientId,
            user_id: userId
          })));
        if (addError) throw addError;
      }

      toast({ title: 'Success', description: 'Board members updated successfully.' });
      return true;

    } catch (err) {
      console.error('Error saving board members:', err);
      toast({ variant: 'destructive', title: 'Error', description: err.message });
      return false;
    } finally {
      setLoading(false);
    }
  }, [toast]);

  return {
    loading,
    error,
    fetchBoardMembers,
    fetchAvailableUsers,
    saveBoardMembers
  };
}
