import { useState, useCallback } from 'react';
import { supabase } from '@/config/supabase';

export const useTeamMembership = (teamId) => {
  const [loading, setLoading] = useState(false);
  const [memberships, setMemberships] = useState([]);

  const loadMemberships = useCallback(async () => {
    if (!teamId) return;
    
    setLoading(true);
    try {
      const { data, error } = await supabase
        .from('team_memberships')
        .select(`
          *,
          user:users(id, email, name)
        `)
        .eq('teamId', teamId);

      if (error) throw error;
      setMemberships(data || []);
    } catch (error) {
      console.error('Failed to fetch memberships:', error);
    } finally {
      setLoading(false);
    }
  }, [teamId]);

  const addMembership = async (values) => {
    const { data, error } = await supabase
      .from('team_memberships')
      .insert([{ ...values, teamId }])
      .select()
      .single();

    if (error) throw error;
    await loadMemberships();
    return data;
  };

  const updateMembership = async (id, values) => {
    const { data, error } = await supabase
      .from('team_memberships')
      .update(values)
      .eq('id', id)
      .select()
      .single();

    if (error) throw error;
    await loadMemberships();
    return data;
  };

  const deleteMembership = async (id) => {
    const { error } = await supabase
      .from('team_memberships')
      .delete()
      .eq('id', id);

    if (error) throw error;
    await loadMemberships();
  };

  return {
    loading,
    memberships,
    loadMemberships,
    addMembership,
    updateMembership,
    deleteMembership,
  };
};