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

export function useRemoveProxyText() {
  const [isRemoving, setIsRemoving] = useState(false);
  const { toast } = useToast();

  const removeProxyText = async (clientId) => {
    if (!clientId) return 0;

    setIsRemoving(true);
    let updatedCount = 0;
    let errorCount = 0;

    try {
      const { data: owners, error: fetchError } = await supabase
        .from('property_owners')
        .select('id, owner_name, show_proxy_text')
        .eq('client_id', clientId);

      if (fetchError) throw fetchError;

      const updates = owners.reduce((acc, owner) => {
        let needsUpdate = false;
        let newName = owner.owner_name;
        let newProxyText = owner.show_proxy_text;

        const proxyPattern = /\s*[\(-]?\s*Proxy.*?\)?/gi;
        if (proxyPattern.test(newName)) {
            newName = newName.replace(proxyPattern, '').trim();
            needsUpdate = true;
        }

        if (newProxyText !== null && newProxyText !== '') {
            newProxyText = null;
            needsUpdate = true;
        }

        if (needsUpdate) {
            acc.push({
                id: owner.id,
                owner_name: newName,
                show_proxy_text: newProxyText
            });
        }
        return acc;
      }, []);

      const updatePromises = updates.map(update => 
          supabase
            .from('property_owners')
            .update({ 
                owner_name: update.owner_name, 
                show_proxy_text: update.show_proxy_text 
            })
            .eq('id', update.id)
            .then(({ error }) => {
                if (error) throw error;
                return 1;
            })
            .catch(err => {
                console.error(`Failed to update owner ${update.id}:`, err);
                errorCount++;
                return 0;
            })
      );

      const results = await Promise.all(updatePromises);
      updatedCount = results.reduce((a, b) => a + b, 0);

      if (errorCount > 0) {
          toast({
              variant: "destructive",
              title: "Partial Success",
              description: `Updated ${updatedCount} records, but failed on ${errorCount}.`
          });
      }

    } catch (error) {
      console.error("Error removing proxy text:", error);
      toast({
        variant: "destructive",
        title: "Error",
        description: "Failed to remove proxy text. Please try again."
      });
      throw error;
    } finally {
      setIsRemoving(false);
    }

    return updatedCount;
  };

  return {
    removeProxyText,
    isRemoving
  };
}
