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

export function useProjectDetails(projectId) {
  const [project, setProject] = useState(null);
  const [loading, setLoading] = useState(true);

  const fetchData = async () => {
    try {
      setLoading(true);
      const { data, error } = await supabase
        .from('projects')
        .select('*')
        .eq('id', projectId)
        .single();

      if (error) throw error;
      setProject(data);
    } catch (err) {
      console.error("Error fetching project details:", err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (!projectId) return;
    fetchData();

    const sub = supabase.channel(`project-${projectId}`)
      .on('postgres_changes', { event: '*', schema: 'public', table: 'projects', filter: `id=eq.${projectId}` }, fetchData)
      .subscribe();

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

  return { project, loading, refetch: fetchData };
}
