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

export function useSubcategoryManager() {
  const [subcategories, setSubcategories] = useState([]);
  const [loading, setLoading] = useState(false);
  const { toast } = useToast();

  const fetchSubcategories = useCallback(async () => {
    setLoading(true);
    try {
      const { data, error } = await supabase
        .from('fee_schedule_subcategories')
        .select('*')
        .order('name');

      if (error) throw error;
      setSubcategories(data || []);
      return data;
    } catch (error) {
      console.error('Error fetching subcategories:', error);
      toast({
        variant: "destructive",
        title: "Error",
        description: "Failed to load subcategories.",
      });
      return [];
    } finally {
      setLoading(false);
    }
  }, [toast]);

  const addSubcategory = async (name) => {
    setLoading(true);
    try {
      const exists = subcategories.some(s => s.name.toLowerCase() === name.trim().toLowerCase());
      if (exists) {
        throw new Error("Subcategory already exists");
      }

      const { data, error } = await supabase
        .from('fee_schedule_subcategories')
        .insert([{ 
          name: name.trim(),
          is_custom: true 
        }])
        .select()
        .single();

      if (error) throw error;

      setSubcategories(prev => [...prev, data].sort((a, b) => a.name.localeCompare(b.name)));
      toast({
        title: "Success",
        description: "Subcategory added successfully.",
      });
      return data;
    } catch (error) {
      console.error('Error adding subcategory:', error);
      toast({
        variant: "destructive",
        title: "Error",
        description: error.message || "Failed to add subcategory.",
      });
      throw error;
    } finally {
      setLoading(false);
    }
  };

  const deleteSubcategory = async (id) => {
    setLoading(true);
    try {
      const { count, error: countError } = await supabase
        .from('fee_schedules')
        .select('*', { count: 'exact', head: true })
        .eq('subcategory', subcategories.find(s => s.id === id)?.name);
      
      if (countError) throw countError;

      if (count > 0) {
        throw new Error(`Cannot delete: This subcategory is used by ${count} fee schedule items.`);
      }

      const { error } = await supabase
        .from('fee_schedule_subcategories')
        .delete()
        .eq('id', id);

      if (error) throw error;

      setSubcategories(prev => prev.filter(s => s.id !== id));
      toast({
        title: "Success",
        description: "Subcategory deleted.",
      });
    } catch (error) {
      console.error('Error deleting subcategory:', error);
      toast({
        variant: "destructive",
        title: "Error",
        description: error.message || "Failed to delete subcategory.",
      });
      throw error;
    } finally {
      setLoading(false);
    }
  };

  return {
    subcategories,
    loading,
    fetchSubcategories,
    addSubcategory,
    deleteSubcategory
  };
}
