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

export const useTeams = (pagination, sorter) => {
  const [teams, setTeams] = useState([]);
  const [loading, setLoading] = useState(false);

  const fetchTeams = useCallback(async (params = {}) => {
    try {
      setLoading(true);
      const { data, total } = await teamService.getTeams({
        page: params.current || pagination.current,
        pageSize: params.pageSize || pagination.pageSize,
        orderBy: params.field || sorter.field,
        ascending: params.order === 'ascend',
       ...(params?.search!==''?{searchQuery:params.search}:{})
      });
      setTeams(data);
      return { data, total };
      
    } catch (error) {
      console.error(error);
      message.error('获取团队列表失败');
    } finally {
      setLoading(false);
    }
  }, [pagination.current, pagination.pageSize, sorter.field, sorter.order]);

  const createTeam = async (values) => {
    try {
      const newTeam = await teamService.createTeam(values);
      setTeams(prev => [...prev, newTeam]);
      return newTeam;
    } catch (error) {
      message.error('Failed to create team');
      throw error;
    }
  };

  const updateTeam = async (id, values) => {
    try {
      const updatedTeam = await teamService.updateTeam(id, values);
      setTeams(prev => prev.map(team => 
        team.id === id ? updatedTeam : team
      ));
      return updatedTeam;
    } catch (error) {
      message.error('Failed to update team');
      throw error;
    }
  };

  const deleteTeam = async (id) => {
    try {
      await teamService.deleteTeam(id);
      setTeams(prev => prev.filter(team => team.id !== id));
    } catch (error) {
      throw error;
    }
  };

  return {
    teams,
    loading,
    fetchTeams,
    createTeam,
    updateTeam,
    deleteTeam,
  };
};