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

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

  const fetchTemplates = useCallback(async () => {
    setLoading(true);
    try {
      const { data, error } = await supabase
        .from('notify_board_templates')
        .select('*')
        .order('created_at', { ascending: false });

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

  const createTemplate = async (templateData) => {
    setLoading(true);
    try {
      const { data, error } = await supabase
        .from('notify_board_templates')
        .insert([{
          ...templateData,
          created_by: (await supabase.auth.getUser()).data.user?.id
        }])
        .select()
        .single();

      if (error) throw error;
      
      toast({
        title: "Success",
        description: "Template created successfully."
      });
      return data;
    } catch (error) {
      console.error('Error creating template:', error);
      toast({
        variant: "destructive",
        title: "Error",
        description: error.message
      });
      throw error;
    } finally {
      setLoading(false);
    }
  };

  const updateTemplate = async (id, updates) => {
    setLoading(true);
    try {
      const { data, error } = await supabase
        .from('notify_board_templates')
        .update(updates)
        .eq('id', id)
        .select()
        .single();

      if (error) throw error;

      toast({
        title: "Success",
        description: "Template updated successfully."
      });
      return data;
    } catch (error) {
      console.error('Error updating template:', error);
      toast({
        variant: "destructive",
        title: "Error",
        description: error.message
      });
      throw error;
    } finally {
      setLoading(false);
    }
  };

  const deleteTemplate = async (id) => {
    setLoading(true);
    try {
      const { error } = await supabase
        .from('notify_board_templates')
        .delete()
        .eq('id', id);

      if (error) throw error;

      toast({
        title: "Success",
        description: "Template deleted successfully."
      });
      return true;
    } catch (error) {
      console.error('Error deleting template:', error);
      toast({
        variant: "destructive",
        title: "Error",
        description: "Failed to delete template."
      });
      throw error;
    } finally {
      setLoading(false);
    }
  };

  return {
    loading,
    fetchTemplates,
    createTemplate,
    updateTemplate,
    deleteTemplate
  };
}
