import { useState, useCallback } from 'react';
import { message } from 'antd';
import { teamMembershipService } from '@/services/supabase/teamMembership';

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

  const fetchMemberships = useCallback(async () => {
    if (!teamId) return;
    
    try {
      setLoading(true);
      const data = await teamMembershipService.getMemberships(teamId);
      setMemberships(data);
    } catch (error) {
      message.error('Failed to fetch team memberships');
      console.error(error);
    } finally {
      setLoading(false);
    }
  }, [teamId]);

  const createMembership = async (values) => {
    try {
      const newMembership = await teamMembershipService.createMembership({
        ...values,
        teamId,
      });
      setMemberships(prev => [...prev, newMembership]);
      message.success('Member added successfully');
      return newMembership;
    } catch (error) {
      message.error('Failed to add member');
      throw error;
    }
  };

  const updateMembership = async (id, values) => {
    try {
      const updatedMembership = await teamMembershipService.updateMembership(id, values);
      setMemberships(prev => prev.map(membership => 
        membership.id === id ? updatedMembership : membership
      ));
      message.success('Member updated successfully');
      return updatedMembership;
    } catch (error) {
      message.error('Failed to update member');
      throw error;
    }
  };

  const deleteMembership = async (id) => {
    try {
      await teamMembershipService.deleteMembership(id);
      setMemberships(prev => prev.filter(membership => membership.id !== id));
      message.success('Member removed successfully');
    } catch (error) {
      message.error('Failed to remove member');
      throw error;
    }
  };

  return {
    memberships,
    loading,
    fetchMemberships,
    createMembership,
    updateMembership,
    deleteMembership,
  };
};