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

export function useBidTags(bidId = null) {
  const [tags, setTags] = useState([]);
  const [allTags, setAllTags] = useState([]);
  const [loading, setLoading] = useState(false);
  const { toast } = useToast();

  const fetchTags = useCallback(async () => {
    if (!bidId) return;
    setLoading(true);
    try {
      const { data, error } = await supabase
        .from('bid_quote_tags')
        .select('*')
        .eq('bid_quote_id', bidId)
        .order('created_at', { ascending: true });

      if (error) throw error;
      setTags(data || []);
    } catch (error) {
      console.error('Error fetching tags:', error);
    } finally {
      setLoading(false);
    }
  }, [bidId]);

  const fetchAllTags = useCallback(async () => {
    setLoading(true);
    try {
      const { data, error } = await supabase
        .from('bid_quote_tags')
        .select('*');

      if (error) throw error;
      setAllTags(data || []);
    } catch (error) {
      console.error('Error fetching all tags:', error);
    } finally {
        if (!bidId) setLoading(false);
    }
  }, [bidId]);

  useEffect(() => {
    if (bidId) {
      fetchTags();
      const channel = supabase
        .channel(`bid_tags_${bidId}`)
        .on(
          'postgres_changes',
          { event: '*', schema: 'public', table: 'bid_quote_tags', filter: `bid_quote_id=eq.${bidId}` },
          () => {
            fetchTags();
            fetchAllTags();
          }
        )
        .subscribe();

      return () => {
        supabase.removeChannel(channel);
      };
    }
  }, [bidId, fetchTags, fetchAllTags]);

  useEffect(() => {
    fetchAllTags();
    
    const channel = supabase
        .channel('all_bid_tags')
        .on(
          'postgres_changes',
          { event: '*', schema: 'public', table: 'bid_quote_tags' },
          () => {
            fetchAllTags();
          }
        )
        .subscribe();

    return () => {
        supabase.removeChannel(channel);
    };
  }, [fetchAllTags]);

  const addTagToBid = async (targetBidId, tagName, color = 'blue') => {
    try {
      const { data: existingData } = await supabase
          .from('bid_quote_tags')
          .select('id')
          .eq('bid_quote_id', targetBidId)
          .ilike('tag_name', tagName)
          .single();

      if (existingData) {
        toast({ title: "Tag exists", description: "This tag is already added to the bid." });
        return null;
      }

      const { data, error } = await supabase
        .from('bid_quote_tags')
        .insert([{ bid_quote_id: targetBidId, tag_name: tagName, color }])
        .select()
        .single();

      if (error) throw error;
      toast({ title: "Tag added", description: `Added "${tagName}" tag.` });
      if (bidId === targetBidId) {
          fetchTags();
      }
      fetchAllTags(); 
      return data;
    } catch (error) {
      console.error('Error adding tag:', error);
      toast({ variant: "destructive", title: "Error", description: "Failed to add tag." });
      return null;
    }
  };

  const removeTagFromBid = async (tagId) => {
    try {
      const { error } = await supabase
        .from('bid_quote_tags')
        .delete()
        .eq('id', tagId);

      if (error) throw error;
      toast({ title: "Tag removed", description: "Tag removed successfully." });
      
      if (bidId) {
          setTags(prev => prev.filter(t => t.id !== tagId));
      }
      fetchAllTags();
      return true;
    } catch (error) {
      console.error('Error removing tag:', error);
      toast({ variant: "destructive", title: "Error", description: "Failed to remove tag." });
      return false;
    }
  };
  
  const updateTagColor = async (tagId, newColor) => {
      try {
          const { data, error } = await supabase
            .from('bid_quote_tags')
            .update({ color: newColor })
            .eq('id', tagId)
            .select()
            .single();

          if (error) throw error;
          toast({ title: "Updated", description: "Tag color updated." });
          if (bidId) fetchTags();
          fetchAllTags();
          return data;
      } catch (error) {
          console.error('Error updating tag:', error);
          toast({ variant: "destructive", title: "Error", description: "Failed to update tag." });
          return null;
      }
  };

  const uniqueTagsWithCounts = allTags.reduce((acc, tag) => {
    const name = tag.tag_name; 
    
    if (!acc[name]) {
      acc[name] = { count: 0, color: tag.color };
    }
    acc[name].count += 1;
    return acc;
  }, {});

  const availableTags = Object.entries(uniqueTagsWithCounts).map(([name, info]) => ({
    name,
    count: info.count,
    color: info.color
  })).sort((a, b) => b.count - a.count);

  return {
    tags,
    allTags,
    availableTags,
    loading,
    addTagToBid,
    removeTagFromBid,
    updateTagColor,
    refreshTags: fetchTags
  };
}
