import { useState, useEffect } from 'react';
import { supabase } from '@/integrations/supabase/client';

export function useProjects(associationId) {
  const [projects, setProjects] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetchProjects();

    const sub = supabase
      .channel('projects-list')
      .on('postgres_changes', { event: '*', schema: 'public', table: 'projects' }, () => {
        fetchProjects();
      })
      .subscribe();

    return () => {
      supabase.removeChannel(sub);
    };
  }, [associationId]);

  const fetchProjects = async () => {
    try {
      setLoading(true);
      let query = supabase.from('projects').select('*').order('created_at', { ascending: false });
      if (associationId) query = query.eq('association_id', associationId);

      const { data, error } = await query;
      if (error) throw error;
      setProjects(data || []);
    } catch (err) {
      console.error('Error fetching projects:', err);
    } finally {
      setLoading(false);
    }
  };

  const createProject = async (projectData) => {
    const { data, error } = await supabase.from('projects').insert([projectData]).select();
    if (error) throw error;
    return data;
  };

  const updateProject = async (id, projectData) => {
    const { data, error } = await supabase.from('projects').update(projectData).eq('id', id).select();
    if (error) throw error;
    return data;
  };

  const deleteProject = async (id) => {
    const { error } = await supabase.from('projects').delete().eq('id', id);
    if (error) throw error;
  };

  return { projects, loading, createProject, updateProject, deleteProject };
}
