import { useState, useCallback, useEffect } from '@wordpress/element';
import { fetchRules, createRule, updateRule, deleteRule } from '../utils/api';

export const useRules = () => {
  const [rules, setRules] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState(null);

  const loadRules = useCallback(async () => {
    try {
      setIsLoading(true);
      setError(null);
      const response = await fetchRules();
      setRules(response);
    } catch (err) {
      setError(err.message);
    } finally {
      setIsLoading(false);
    }
  }, []);

  const handleCreateRule = useCallback(async (ruleData) => {
    try {
      await createRule(ruleData);
      await loadRules(); // Reload rules after creation
      return true;
    } catch (err) {
      setError(err.message);
      return false;
    }
  }, [loadRules]);

  const handleUpdateRule = useCallback(async (ruleId, ruleData) => {
    try {
      await updateRule(ruleId, ruleData);
      await loadRules(); // Reload rules after update
      return true;
    } catch (err) {
      setError(err.message);
      return false;
    }
  }, [loadRules]);

  const handleDeleteRule = useCallback(async (ruleId) => {
    try {
      await deleteRule(ruleId);
      await loadRules(); // Reload rules after deletion
      return true;
    } catch (err) {
      setError(err.message);
      return false;
    }
  }, [loadRules]);

  // Load rules on mount
  useEffect(() => {
    loadRules();
  }, [loadRules]);

  return {
    rules,
    isLoading,
    error,
    createRule: handleCreateRule,
    updateRule: handleUpdateRule,
    deleteRule: handleDeleteRule,
    reloadRules: loadRules,
  };
};