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

export function useEmailHistory() {
  const [loading, setLoading] = useState(false);

  const getEmailHistory = async ({ recipient, status, page = 1, pageSize = 20 }) => {
    setLoading(true);
    try {
      let query = supabase
        .from('documents')
        .select('*', { count: 'exact' })
        .eq('category', 'email');

      if (recipient) {
        query = query.ilike('title', `%${recipient}%`);
      }

      const from = (page - 1) * pageSize;
      const to = from + pageSize - 1;

      const { data, count, error } = await query
        .order('created_at', { ascending: false })
        .range(from, to);

      if (error) throw error;
      return { data, count };
    } catch (err) {
      console.error('Error fetching email history:', err);
      return { data: [], count: 0 };
    } finally {
      setLoading(false);
    }
  };

  return { getEmailHistory, loading };
}
