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

export function useNotifyBoardClients(targetClientId = null) {
  const [clients, setClients] = useState([]);
  const [additionalEmails, setAdditionalEmails] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [isSyncing, setIsSyncing] = useState(false);
  const { toast } = useToast();
  
  const isMounted = useRef(true);

  useEffect(() => {
    isMounted.current = true;
    return () => {
      isMounted.current = false;
    };
  }, []);

  useEffect(() => {
    if (targetClientId) {
      setAdditionalEmails([]);
      setLoading(true);
    }
  }, [targetClientId]);

  const fetchClients = useCallback(async (showLoading = true) => {
    if (showLoading && isMounted.current) setLoading(true);
    if (isMounted.current) setIsSyncing(true);
    
    try {
      const { data: clientsData, error: clientsError } = await supabase
        .from('clients')
        .select('id, name, email, notice_logo, logo_url')
        .order('name');
      
      if (clientsError) throw clientsError;

      let emailQuery = supabase
        .from('client_email_addresses')
        .select('client_id, email_address');
      
      if (targetClientId) {
        emailQuery = emailQuery.eq('client_id', targetClientId);
      }

      const { data: emailsData, error: emailsError } = await emailQuery;
        
      if (emailsError) {
        console.warn('Error fetching additional emails:', emailsError);
      }

      if (isMounted.current) {
        setClients(clientsData || []);
        
        const uniqueEmails = (emailsData || []).filter((email, index, self) =>
          index === self.findIndex((e) => (
            e.email_address === email.email_address && e.client_id === email.client_id
          ))
        );

        setAdditionalEmails(uniqueEmails);
        setError(null);
      }
    } catch (err) {
      console.error('Error fetching Notify Board clients:', err);
      if (isMounted.current) {
        setError(err.message);
        toast({
          variant: "destructive",
          title: "Sync Error",
          description: "Failed to load client list. Please refresh."
        });
      }
    } finally {
      if (isMounted.current) {
        setLoading(false);
        setIsSyncing(false);
      }
    }
  }, [toast, targetClientId]);

  useEffect(() => {
    fetchClients(true);
  }, [fetchClients]);

  useEffect(() => {
    const clientsChannel = supabase
      .channel('notify-board-clients-changes')
      .on(
        'postgres_changes',
        { event: '*', schema: 'public', table: 'clients' },
        (payload) => {
          console.log('Client change detected:', payload);
          fetchClients(false); 
        }
      )
      .subscribe();

    const emailFilter = targetClientId 
      ? `client_id=eq.${targetClientId}` 
      : undefined;

    const emailsChannel = supabase
      .channel(`notify-board-emails-changes-${targetClientId || 'all'}`)
      .on(
        'postgres_changes',
        { 
          event: '*', 
          schema: 'public', 
          table: 'client_email_addresses',
          filter: emailFilter
        },
        (payload) => {
          console.log('Email change detected:', payload);
          fetchClients(false);
        }
      )
      .subscribe();

    return () => {
      supabase.removeChannel(clientsChannel);
      supabase.removeChannel(emailsChannel);
    };
  }, [fetchClients, targetClientId]);

  return {
    clients,
    additionalEmails,
    loading,
    error,
    isSyncing,
    refresh: () => fetchClients(true)
  };
}
