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

const ProxyTextToggleContext = createContext(null);

export const useProxyTextToggle = () => {
  const context = useContext(ProxyTextToggleContext);
  if (!context) {
    throw new Error('useProxyTextToggle must be used within a ProxyTextToggleProvider');
  }
  return context;
};

export const ProxyTextToggleProvider = ({ children }) => {
  const { toast } = useToast();
  const [isToggling, setIsToggling] = useState(false);
  const [proxyTextStatus, setProxyTextStatus] = useState({});

  const fetchProxyTextStatus = useCallback(async (clientId) => {
    if (!clientId) return;
    try {
      const { data, error } = await supabase
        .from('association_info')
        .select('sync_settings')
        .eq('id', clientId)
        .single();
      
      if (error && error.code !== 'PGRST116') {
         console.error("Error fetching proxy status:", error);
         return;
      }

      const isEnabled = data?.sync_settings?.show_proxy_on_signin ?? true;
      setProxyTextStatus(prev => ({ ...prev, [clientId]: isEnabled }));
      return isEnabled;
    } catch (err) {
      console.error("Error in fetchProxyTextStatus:", err);
      return true;
    }
  }, []);

  const toggleProxyText = async (clientId, currentState) => {
    if (!clientId) return;
    setIsToggling(true);
    const newState = !currentState;

    try {
      const { data: currentData } = await supabase
        .from('association_info')
        .select('sync_settings')
        .eq('id', clientId)
        .single();
      
      const currentSettings = currentData?.sync_settings || {};
      const newSettings = { ...currentSettings, show_proxy_on_signin: newState };

      const { error } = await supabase
        .from('association_info')
        .upsert({ 
            id: clientId, 
            sync_settings: newSettings,
            updated_at: new Date().toISOString()
        });

      if (error) throw error;

      setProxyTextStatus(prev => ({ ...prev, [clientId]: newState }));
      
      toast({
        title: newState ? "Proxy Text Enabled" : "Proxy Text Disabled",
        description: newState 
          ? "Proxy information will appear on sign-in sheets." 
          : "Proxy information will be hidden on sign-in sheets.",
      });
      
    } catch (error) {
      console.error("Error toggling proxy text:", error);
      toast({
        variant: "destructive",
        title: "Error",
        description: "Failed to update proxy text settings."
      });
    } finally {
      setIsToggling(false);
    }
  };

  return (
    <ProxyTextToggleContext.Provider value={{ 
      proxyTextStatus, 
      fetchProxyTextStatus, 
      toggleProxyText, 
      isToggling 
    }}>
      {children}
    </ProxyTextToggleContext.Provider>
  );
};
