import { useState, useCallback } from 'react';
import { supabase } from '@/integrations/supabase/client';
import { toast } from 'sonner';

export function useManagementReports() {
  const [loading, setLoading] = useState(false);
  const [reports, setReports] = useState([]);

  const fetchReports = useCallback(async () => {
    setLoading(true);
    try {
      const { data, error } = await supabase
        .from('documents')
        .select('*')
        .eq('category', 'management_report')
        .order('created_at', { ascending: false });

      if (error) throw error;
      setReports(data || []);
      return data;
    } catch (error) {
      console.error('Error fetching reports:', error);
      toast.error('Failed to load saved reports');
      return [];
    } finally {
      setLoading(false);
    }
  }, []);

  const deleteReport = useCallback(async (reportId) => {
    setLoading(true);
    try {
      const { error } = await supabase
        .from('documents')
        .delete()
        .eq('id', reportId);

      if (error) throw error;
      setReports(prev => prev.filter(r => r.id !== reportId));
      toast.success('Report deleted');
    } catch (error) {
      console.error('Error deleting report:', error);
      toast.error('Failed to delete report');
    } finally {
      setLoading(false);
    }
  }, []);

  return { reports, loading, fetchReports, deleteReport };
}
