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

export const useTeamData = () => {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  const loadData = useCallback(async ({ 
    pagination = {}, 
    filters = {}, 
    sorter = {},
    search = '' 
  } = {}) => {
    setLoading(true);
    try {
      let query = supabase
        .from('teams')
        .select(`
          *,
          memberships:team_memberships(
            id,
            role,
            user:users(id, email, name)
          ),
          tags(id, name)
        `);

      // Add search condition
      if (search) {
        query = query.ilike('name', `%${search}%`);
      }

      // Add sorting
      if (sorter.field) {
        const order = sorter.order === 'descend' ? 'desc' : 'asc';
        query = query.order(sorter.field, { ascending: order === 'asc' });
      }

      // Add pagination
      const from = ((pagination.current || 1) - 1) * (pagination.pageSize || 10);
      const to = from + (pagination.pageSize || 10) - 1;
      query = query.range(from, to);

      const { data: teams, count } = await query;

      setData(teams || []);
      setPagination({
        ...pagination,
        total: count || 0,
      });
    } catch (error) {
      console.error('Failed to fetch teams:', error);
    } finally {
      setLoading(false);
    }
  }, []);

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

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

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

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

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

    if (error) throw error;
  };

  return {
    loading,
    data,
    pagination,
    loadData,
    createTeam,
    updateTeam,
    deleteTeam,
  };
};