import { useState, useCallback } from 'react';
import { supabase } from '@/integrations/supabase/client';
import { useToast } from '@/hooks/use-toast';
import { useAuth } from '@/contexts/AuthContext';

export function useReportManagement() {
  const [loading, setLoading] = useState(false);
  const { toast } = useToast();
  const { user } = useAuth();

  const listReports = useCallback(async (clientId, filters = {}) => {
    try {
      setLoading(true);
      let query = supabase
        .from('saved_reports')
        .select(`
          *,
          created_by_user:users!created_by(full_name)
        `)
        .order('updated_at', { ascending: false });

      if (clientId) {
        query = query.eq('client_id', clientId);
      }

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

      if (filters.type && filters.type !== 'all') {
        query = query.eq('report_type', filters.type);
      }

      const { data, error } = await query;

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

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

      if (error) throw error;
      return data;
    } catch (error) {
      console.error('Error loading report:', error);
      toast({
        variant: "destructive",
        title: "Error",
        description: "Failed to load the report."
      });
      return null;
    } finally {
      setLoading(false);
    }
  }, [toast]);

  const saveReport = useCallback(async (reportData, id = null) => {
    try {
      setLoading(true);
      
      const payload = {
        ...reportData,
        updated_at: new Date().toISOString(),
        created_by: user?.id
      };

      let result;
      if (id) {
        const { data, error } = await supabase
          .from('saved_reports')
          .update(payload)
          .eq('id', id)
          .select()
          .single();
        
        if (error) throw error;
        result = data;
        toast({
          title: "Success",
          description: "Report updated successfully."
        });
      } else {
        const { data, error } = await supabase
          .from('saved_reports')
          .insert([{
             ...payload,
             created_at: new Date().toISOString()
          }])
          .select()
          .single();

        if (error) throw error;
        result = data;
        toast({
          title: "Success",
          description: "Report saved successfully."
        });
      }
      return result;
    } catch (error) {
      console.error('Error saving report:', error);
      toast({
        variant: "destructive",
        title: "Error",
        description: "Failed to save the report."
      });
      return null;
    } finally {
      setLoading(false);
    }
  }, [user, toast]);

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

      if (error) throw error;
      
      toast({
        title: "Success",
        description: "Report deleted successfully."
      });
      return true;
    } catch (error) {
      console.error('Error deleting report:', error);
      toast({
        variant: "destructive",
        title: "Error",
        description: "Failed to delete the report."
      });
      return false;
    } finally {
      setLoading(false);
    }
  }, [toast]);

  return {
    loading,
    listReports,
    loadReport,
    saveReport,
    deleteReport
  };
}
