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

export function useClientEmail() {
  const [email, setEmail] = useState('');
  const [loading, setLoading] = useState(false);
  const { toast } = useToast();

  const fetchClientEmail = useCallback(async (associationId) => {
    if (!associationId) return;
    setLoading(true);
    try {
      const { data, error } = await supabase
        .from('associations')
        .select('email')
        .eq('id', associationId)
        .single();
      if (error) throw error;
      setEmail(data?.email || '');
      return data?.email;
    } catch (error) {
      console.error('Error fetching client email:', error);
      toast({ variant: 'destructive', title: 'Error', description: 'Failed to fetch client email.' });
    } finally {
      setLoading(false);
    }
  }, [toast]);

  const updateClientEmail = useCallback(async (associationId, newEmail) => {
    if (!associationId) return;
    setLoading(true);
    try {
      const { error } = await supabase
        .from('associations')
        .update({ email: newEmail })
        .eq('id', associationId);
      if (error) throw error;
      setEmail(newEmail);
      toast({ title: 'Success', description: 'Client email updated successfully.' });
      return true;
    } catch (error) {
      console.error('Error updating client email:', error);
      toast({ variant: 'destructive', title: 'Error', description: 'Failed to update client email.' });
      return false;
    } finally {
      setLoading(false);
    }
  }, [toast]);

  return { email, setEmail, loading, fetchClientEmail, updateClientEmail };
}
