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

export function useBidTagsSimple(bidId = null) {
  const [tags, setTags] = useState([]);
  const [availableTags, setAvailableTags] = useState([]);
  const [loading, setLoading] = useState(false);
  const { toast } = useToast();

  const fetchTags = useCallback(async () => {
    if (!bidId) return;
    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('fetchTags error:', error);
    }
  }, [bidId]);

  const fetchAvailableTags = useCallback(async () => {
    setLoading(true);
    try {
      const { data, error } = await supabase
        .from('bid_tag_definitions')
        .select('*')
        .order('name', { ascending: true });
      if (error) throw error;
      setAvailableTags(data || []);
    } catch (error) {
      console.error('fetchAvailableTags error:', error);
      toast({ variant: "destructive", title: "Error", description: "Failed to load tags." });
      setAvailableTags([]);
    } finally {
      setLoading(false);
    }
  }, [toast]);

  useEffect(() => {
    fetchAvailableTags();
    if (bidId) fetchTags();
  }, [bidId, fetchTags, fetchAvailableTags]);

  const createTagDefinition = async (name, color) => {
    if (!name) return null;
    try {
      const { data: existing, error: checkError } = await supabase
        .from('bid_tag_definitions')
        .select('id')
        .ilike('name', name)
        .maybeSingle();
      if (checkError) throw checkError;
      if (existing) {
        toast({ variant: "destructive", title: "Duplicate", description: "Tag already exists." });
        return null;
      }
      const { data, error } = await supabase
        .from('bid_tag_definitions')
        .insert([{ name, color }])
        .select()
        .single();
      if (error) throw error;
      toast({ title: "Success", description: "Tag created." });
      fetchAvailableTags();
      return data;
    } catch (error) {
      console.error('createTagDefinition error:', error);
      toast({ variant: "destructive", title: "Error", description: "Failed to create tag." });
      return null;
    }
  };

  const deleteTagDefinition = async (id, name) => {
    try {
      const { error: defError } = await supabase.from('bid_tag_definitions').delete().eq('id', id);
      if (defError) throw defError;
      const { error: cleanupError } = await supabase.from('bid_quote_tags').delete().eq('tag_name', name);
      if (cleanupError) console.warn("Cleanup error (non-fatal):", cleanupError);
      toast({ title: "Success", description: "Tag deleted." });
      fetchAvailableTags();
      if (bidId) fetchTags();
    } catch (error) {
      console.error('deleteTagDefinition error:', error);
      toast({ variant: "destructive", title: "Error", description: "Failed to delete tag." });
    }
  };

  const addTagToBid = async (targetBidId, tagName, color) => {
    if (!targetBidId || !tagName) return;
    try {
      const { data: existing, error: checkError } = await supabase
        .from('bid_quote_tags')
        .select('id')
        .eq('bid_quote_id', targetBidId)
        .eq('tag_name', tagName)
        .maybeSingle();
      if (checkError) throw checkError;
      if (existing) return;
      const { error } = await supabase
        .from('bid_quote_tags')
        .insert([{ bid_quote_id: targetBidId, tag_name: tagName, color }]);
      if (error) throw error;
      if (bidId === targetBidId) fetchTags();
    } catch (error) {
      console.error('addTagToBid error:', error);
      toast({ variant: "destructive", title: "Error", description: "Failed to apply tag." });
    }
  };

  const removeTagFromBid = async (targetBidId, tagName) => {
    try {
      const { error } = await supabase
        .from('bid_quote_tags')
        .delete()
        .eq('bid_quote_id', targetBidId)
        .eq('tag_name', tagName);
      if (error) throw error;
      if (bidId === targetBidId) fetchTags();
    } catch (error) {
      console.error('removeTagFromBid error:', error);
      toast({ variant: "destructive", title: "Error", description: "Failed to remove tag." });
    }
  };

  return {
    tags,
    availableTags,
    loading,
    createTagDefinition,
    deleteTagDefinition,
    addTagToBid,
    removeTagFromBid,
    refreshTags: fetchTags,
    refreshAvailable: fetchAvailableTags
  };
}
